Java Code Examples for org.springframework.security.authentication.AuthenticationServiceException

The following examples show how to use org.springframework.security.authentication.AuthenticationServiceException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: api-layer   Source File: RestResponseHandler.java    License: Eclipse Public License 2.0 7 votes vote down vote up
private void handleHttpClientError(@NotNull Exception exception, ErrorType errorType, String genericLogErrorMessage, Object... logParameters) {
    HttpClientErrorException hceException = (HttpClientErrorException) exception;
    switch (hceException.getStatusCode()) {
        case UNAUTHORIZED:
            if (errorType != null) {
                if (errorType.equals(ErrorType.BAD_CREDENTIALS)) {
                    throw new BadCredentialsException(errorType.getDefaultMessage(), exception);
                } else if (errorType.equals(ErrorType.TOKEN_NOT_VALID)) {
                    throw new TokenNotValidException(errorType.getDefaultMessage(), exception);
                } else if (errorType.equals(ErrorType.TOKEN_NOT_PROVIDED)) {
                    throw new TokenNotProvidedException(errorType.getDefaultMessage());
                }
            }
            throw new BadCredentialsException(ErrorType.BAD_CREDENTIALS.getDefaultMessage(), exception);
        case BAD_REQUEST:
            throw new AuthenticationCredentialsNotFoundException(ErrorType.AUTH_CREDENTIALS_NOT_FOUND.getDefaultMessage(), exception);
        case METHOD_NOT_ALLOWED:
            throw new AuthMethodNotSupportedException(ErrorType.AUTH_METHOD_NOT_SUPPORTED.getDefaultMessage());
        default:
            addDebugMessage(exception, genericLogErrorMessage, logParameters);
            throw new AuthenticationServiceException(ErrorType.AUTH_GENERAL.getDefaultMessage(), exception);
    }
}
 
Example 2
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
	if (this.postOnly && !request.getMethod().equals("POST")) {
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	} else {
		String phone = this.obtainPhone(request);
		if (StringUtils.isEmpty(phone)) {
			phone = "";
		}

		phone = phone.trim();
		//把手机号传进SmsCodeAuthenticationToken
		SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(phone);
		this.setDetails(request, authRequest);
		//调用AuthenticationManager
		return this.getAuthenticationManager().authenticate(authRequest);
	}
}
 
Example 3
/**
 * 覆盖授权验证方法
 */
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	if (postOnly && !request.getMethod().equals("POST")) {
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	}
	String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
	Map<String, Object> map = JsonUtil.jsonToMap(body);
	String username = map.get("userName")+"";
	String password = map.get("password")+"";
	//根据不同登录方式,生成不同类型Authentication,如这里的CaptchaAuthenticationToken
	CaptchaAuthenticationToken authRequest = new CaptchaAuthenticationToken(username,password);
	//其他参数,可以是一个字符串,也可以任意对象
	//authRequest.setDetails("其他参数");
	//将未认证Authentication交给AuthenticationManager去认证
	return getAuthenticationManager().authenticate(authRequest);

}
 
Example 4
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    RefreshTokenRequest refreshTokenRequest;
    try {
        refreshTokenRequest = objectMapper.readValue(request.getReader(), RefreshTokenRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid refresh token request payload");
    }

    if (StringUtils.isBlank(refreshTokenRequest.getRefreshToken())) {
        throw new AuthenticationServiceException("Refresh token is not provided");
    }

    RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.getRefreshToken());

    return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token));

}
 
Example 5
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
                                            HttpServletResponse response) throws AuthenticationException {
    if (!HttpMethod.POST.matches(request.getMethod())) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }
    // 获取参数
    String sms = obtainSms(request);
    sms = sms == null ? "" : sms.trim();
    // 需要创建我们自己的授权 token
    SmsAuthenticationToken authRequest = new SmsAuthenticationToken(sms);
    setDetails(request, authRequest);
    // 授权管理器对请求进行授权
    return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 6
Source Project: cola   Source File: OpenIdAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
	if (this.postOnly && !request.getMethod().equals("POST")) {
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	} else {

		String openId = this.obtainOpenId(request);
		if (openId == null) {
			openId = "";
		}

		openId = openId.trim();

		String provider = this.obtainProvider(request);
		if (provider == null) {
			provider = "";
		}

		provider = provider.trim();

		OpenIdAuthenticationToken authRequest = new OpenIdAuthenticationToken(openId, provider);
		this.setDetails(request, authRequest);
		return this.getAuthenticationManager().authenticate(authRequest);
	}
}
 
Example 7
Source Project: cola   Source File: AcAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
	if (this.postOnly && !request.getMethod().equals("POST")) {
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	} else {

		String authorizationCode = this.obtainAuthorizationCode(request);
		if (authorizationCode == null) {
			authorizationCode = "";
		}

		authorizationCode = authorizationCode.trim();

		String provider = this.obtainProvider(request);
		if (provider == null) {
			provider = "";
		}

		provider = provider.trim();

		AcAuthenticationToken authRequest = new AcAuthenticationToken(authorizationCode, provider);
		this.setDetails(request, authRequest);
		return this.getAuthenticationManager().authenticate(authRequest);
	}
}
 
Example 8
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    //判断是不是post请求
    if (postOnly && !request.getMethod().equals(HttpMethod.POST.toString())) {
        throw new AuthenticationServiceException("认证方法不支持: " + request.getMethod());
    }
    //从请求中获取手机号码
    String mobile = obtainMobile(request);
    if (mobile == null) {
        mobile = "";
    }
    mobile = mobile.trim();
    //创建SmsCodeAuthenticationToken(未认证)
    SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);
    //设置用户信息
    setDetails(request, authRequest);
    //返回Authentication实例
    return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 9
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
	if (this.postOnly && !request.getMethod().equals("POST")) {
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	} else {
		String phone = this.obtainPhone(request);
		if (StringUtils.isEmpty(phone)) {
			phone = "";
		}

		phone = phone.trim();
		//把手机号传进SmsCodeAuthenticationToken
		SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(phone);
		this.setDetails(request, authRequest);
		//调用AuthenticationManager
		return this.getAuthenticationManager().authenticate(authRequest);
	}
}
 
Example 10
/**
 * 覆盖授权验证方法
 */
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	if (postOnly && !request.getMethod().equals("POST")) {
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	}
	String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
	Map<String, Object> map = JsonUtil.jsonToMap(body);
	String username = map.get("userName")+"";
	String password = map.get("password")+"";
	//根据不同登录方式,生成不同类型Authentication,如这里的CaptchaAuthenticationToken
	CaptchaAuthenticationToken authRequest = new CaptchaAuthenticationToken(username,password);
	//其他参数,可以是一个字符串,也可以任意对象
	//authRequest.setDetails("其他参数");
	//将未认证Authentication交给AuthenticationManager去认证
	return getAuthenticationManager().authenticate(authRequest);

}
 
Example 11
Source Project: blog-sample   Source File: SmsCodeAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }

    String mobile = obtainMobile(request);

    if (mobile == null) {
        mobile = "";
    }

    mobile = mobile.trim();

    SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);

    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 12
Source Project: blog-sample   Source File: SmsCodeAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }

    String mobile = obtainMobile(request);

    if (mobile == null) {
        mobile = "";
    }

    mobile = mobile.trim();

    SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);

    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 13
Source Project: Taroco   Source File: SmsCodeAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }
    String principal;
    String credentials;
    // 1. 从请求中获取参数 mobile + smsCode
    principal = obtainParameter(request, SPRING_SECURITY_RESTFUL_PHONE_KEY);
    credentials = obtainParameter(request, SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY);
    principal = principal.trim();
    SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(principal, credentials);
    this.setDetails(request, authRequest);
    // 3. 返回 authenticated 方法的返回值
    return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 14
Source Project: Taroco   Source File: MobileTokenAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }

    AbstractAuthenticationToken authRequest;
    String principal;
    String credentials;

    // 手机验证码登陆
    principal = obtainParameter(request, SPRING_SECURITY_RESTFUL_PHONE_KEY);
    credentials = obtainParameter(request, SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY);

    principal = principal.trim();
    authRequest = new MobileTokenAuthenticationToken(principal, credentials);
    setDetails(request, authRequest);
    return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 15
Source Project: pig   Source File: MobileAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
                                            HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }

    String mobile = obtainMobile(request);

    if (mobile == null) {
        mobile = "";
    }

    mobile = mobile.trim();

    MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile);

    setDetails(request, mobileAuthenticationToken);

    return this.getAuthenticationManager().authenticate(mobileAuthenticationToken);
}
 
Example 16
Source Project: fw-cloud-framework   Source File: AjaxAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
		throws AuthenticationException {
	if (postOnly && !request.getMethod().equals(HttpMethod.POST.name()))
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());

	String mobile = obtainMobile(request);
	if (StringHelper.isBlank(mobile))
		mobile = "";

	AjaxAuthenticationToken ajaxAuthenticationToken = new AjaxAuthenticationToken(mobile.trim());

	setDetails(request, ajaxAuthenticationToken);

	return this.getAuthenticationManager()
			.authenticate(ajaxAuthenticationToken);
}
 
Example 17
Source Project: Groza   Source File: RefreshTokenProcessingFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if(log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    RefreshTokenRequest refreshTokenRequest;
    try {
        refreshTokenRequest = objectMapper.readValue(request.getReader(), RefreshTokenRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid refresh token request payload");
    }

    if (StringUtils.isBlank(refreshTokenRequest.getRefreshToken())) {
        throw new AuthenticationServiceException("Refresh token is not provided");
    }

    RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.getRefreshToken());

    return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token));
}
 
Example 18
@SuppressWarnings("ConstantConditions")
@Test
public void shouldFailToAuthenticateUsingJWKIfMissingProvider() throws Exception {
    Jwk jwk = mock(Jwk.class);

    JwkProvider jwkProvider = null;
    KeyPair keyPair = RSAKeyPair();
    when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(AuthenticationServiceException.class);
    exception.expectMessage("Missing jwk provider");
    provider.authenticate(authentication);
}
 
Example 19
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfKeyIdDoesNotMatch() throws Exception {
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenThrow(SigningKeyNotFoundException.class);
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(AuthenticationServiceException.class);
    exception.expectMessage("Could not retrieve jwks from issuer");
    exception.expectCause(Matchers.<Throwable>instanceOf(SigningKeyNotFoundException.class));
    provider.authenticate(authentication);
}
 
Example 20
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfPublicKeyIsInvalid() throws Exception {
    Jwk jwk = mock(Jwk.class);
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
    when(jwk.getPublicKey()).thenThrow(InvalidPublicKeyException.class);
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(AuthenticationServiceException.class);
    exception.expectMessage("Could not retrieve public key from issuer");
    exception.expectCause(Matchers.<Throwable>instanceOf(InvalidPublicKeyException.class));
    provider.authenticate(authentication);
}
 
Example 21
@SuppressWarnings("unchecked")
@Test
public void shouldFailToAuthenticateUsingJWKIfKeyIdCannotBeObtained() throws Exception {
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenThrow(JwkException.class);
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, "test-issuer", "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    exception.expect(AuthenticationServiceException.class);
    exception.expectMessage("Cannot authenticate with jwt");
    exception.expectCause(Matchers.<Throwable>instanceOf(JwkException.class));
    provider.authenticate(authentication);
}
 
Example 22
Source Project: api-layer   Source File: ZosmfServiceFacade.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Method return base information about z/OSMF which is currently in use. Method use cache to reduce amount of calls.
 *
 * @param zosmfServiceId id of z/OSMF service (see static definition)
 * @return ZosmfInfo, which contains version of z/OSMF, domain and realm (domain)
 */
@Cacheable("zosmfInfo")
public ZosmfInfo getZosmfInfo(String zosmfServiceId) {
    final String url = getURI(zosmfServiceId) + ZOSMF_INFO_END_POINT;
    final HttpHeaders headers = new HttpHeaders();
    headers.add(ZOSMF_CSRF_HEADER, "");

    try {
        final ResponseEntity<ZosmfInfo> info = restTemplateWithoutKeystore.exchange(
            url, HttpMethod.GET, new HttpEntity<>(headers), ZosmfInfo.class
        );

        ZosmfInfo zosmfInfo = info.getBody();
        if ((zosmfInfo != null) && StringUtils.isEmpty(zosmfInfo.getSafRealm())) {
            apimlLog.log("apiml.security.zosmfDomainIsEmpty", ZOSMF_DOMAIN);
            throw new AuthenticationServiceException("z/OSMF domain cannot be read.");
        }

        return zosmfInfo;
    } catch (RuntimeException re) {
        meProxy.evictCaches();
        throw handleExceptionOnCall(url, re);
    }
}
 
Example 23
Source Project: api-layer   Source File: AbstractZosmfService.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Method handles exception from REST call to z/OSMF into internal exception. It convert original exception into
 * custom one with better messages and types for subsequent treatment.
 *
 * @param url URL of invoked REST endpoint
 * @param re original exception
 * @return translated exception
 */
protected RuntimeException handleExceptionOnCall(String url, RuntimeException re) {
    if (re instanceof ResourceAccessException) {
        apimlLog.log("org.zowe.apiml.security.serviceUnavailable", url, re.getMessage());
        return new ServiceNotAccessibleException("Could not get an access to z/OSMF service.");
    }

    if (re instanceof HttpClientErrorException.Unauthorized) {
        return new BadCredentialsException("Username or password are invalid.");
    }

    if (re instanceof RestClientException) {
        apimlLog.log("org.zowe.apiml.security.generic", re.getMessage(), url);
        return new AuthenticationServiceException("A failure occurred when authenticating.", re);
    }

    return re;
}
 
Example 24
Source Project: api-layer   Source File: GatewayHealthIndicator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) {
    boolean apiCatalogUp = !this.discoveryClient.getInstances(CoreService.API_CATALOG.getServiceId()).isEmpty();

    // When DS goes 'down' after it was already 'up', the new status is not shown. This is probably feature of
    // Eureka client which caches the status of services. When DS is down the cache is not refreshed.
    boolean discoveryUp = !this.discoveryClient.getInstances(CoreService.DISCOVERY.getServiceId()).isEmpty();

    boolean authUp = true;
    if (!authConfigurationProperties.getProvider().equalsIgnoreCase(LoginProvider.DUMMY.toString())) {
        try {
            authUp = !this.discoveryClient.getInstances(authConfigurationProperties.validatedZosmfServiceId()).isEmpty();
        } catch (AuthenticationServiceException ex) {
            System.exit(-1);
        }
    }

    int gatewayCount = this.discoveryClient.getInstances(CoreService.GATEWAY.getServiceId()).size();

    builder.status(toStatus(discoveryUp))
        .withDetail(CoreService.API_CATALOG.getServiceId(), toStatus(apiCatalogUp).getCode())
        .withDetail(CoreService.DISCOVERY.getServiceId(), toStatus(discoveryUp).getCode())
        .withDetail(CoreService.AUTH.getServiceId(), toStatus(authUp).getCode())
        .withDetail("gatewayCount", gatewayCount);
}
 
Example 25
@Test
public void notValidZosmfResponse() {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, COOKIE1);
    headers.add(HttpHeaders.SET_COOKIE, COOKIE2);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(new ZosmfServiceFacade.ZosmfInfo(), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(AuthenticationServiceException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not AuthenticationServiceException");
    assertEquals("z/OSMF domain cannot be read.", exception.getMessage());
}
 
Example 26
@Test
public void noDomainInResponse() throws IOException {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.SET_COOKIE, COOKIE1);
    headers.add(HttpHeaders.SET_COOKIE, COOKIE2);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenReturn(new ResponseEntity<>(getResponse(false), headers, HttpStatus.OK));

    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(AuthenticationServiceException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not AuthenticationServiceException");
    assertEquals("z/OSMF domain cannot be read.", exception.getMessage());
}
 
Example 27
@Test
public void shouldThrowNewExceptionIfRestClientException() {
    authConfigurationProperties.setZosmfServiceId(ZOSMF);

    final Application application = createApplication(zosmfInstance);
    when(discovery.getApplication(ZOSMF)).thenReturn(application);
    when(restTemplate.exchange(Mockito.anyString(),
        Mockito.eq(HttpMethod.GET),
        Mockito.any(),
        Mockito.<Class<Object>>any()))
        .thenThrow(RestClientException.class);
    ZosmfService zosmfService = createZosmfService();
    ZosmfAuthenticationProvider zosmfAuthenticationProvider =
        new ZosmfAuthenticationProvider(authenticationService, zosmfService);

    Exception exception = assertThrows(AuthenticationServiceException.class,
        () -> zosmfAuthenticationProvider.authenticate(usernamePasswordAuthentication),
        "Expected exception is not AuthenticationServiceException");
    assertEquals("A failure occurred when authenticating.", exception.getMessage());
}
 
Example 28
/**
 * Attempt authentication authentication.
 *
 * @param request  the request
 * @param response the response
 *
 * @return the authentication
 *
 * @throws AuthenticationException the authentication exception
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
		throws AuthenticationException {
	if (postOnly && !POST.equals(request.getMethod())) {
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	}

	String mobile = obtainMobile(request);

	if (mobile == null) {
		mobile = "";
	}

	mobile = mobile.trim();

	SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile);

	// Allow subclasses to set the "details" property
	setDetails(request, authRequest);

	return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 29
Source Project: multitenancy   Source File: CustomAuthenticationFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {
    if (!request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }

    CustomAuthenticationToken authRequest = getAuthRequest(request);

    // put in tenant context threadlocal
    String tenant = authRequest.getTenant();
    TenantContextHolder.setTenantId(tenant);

    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}
 
Example 30
Source Project: SpringAll   Source File: SmsAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
public Authentication attemptAuthentication(HttpServletRequest request,
                                            HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }

    String mobile = obtainMobile(request);

    if (mobile == null) {
        mobile = "";
    }

    mobile = mobile.trim();

    SmsAuthenticationToken authRequest = new SmsAuthenticationToken(mobile);

    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}