org.springframework.security.authentication.AuthenticationServiceException Java Examples

The following examples show how to use org.springframework.security.authentication.AuthenticationServiceException. 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 File: RestResponseHandler.java    From api-layer with 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
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@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 #3
Source File: SmsAuthenticationFilter.java    From SpringAll with 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);
}
 
Example #4
Source File: CaptchaAuthenticationFilter.java    From codeway_service with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 覆盖授权验证方法
 */
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 #5
Source File: SmsAuthenticationFilter.java    From SpringAll with 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);
}
 
Example #6
Source File: OpenIdAuthenticationFilter.java    From cola with 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 File: RefreshTokenProcessingFilter.java    From IOT-Technical-Guide with 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())) {
        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 #8
Source File: SmsAuthenticationFilter.java    From SpringAll with 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);
}
 
Example #9
Source File: SmsCodeAuthenticationFilter.java    From blog-sample with 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 #10
Source File: SmsCodeAuthenticationFilter.java    From blog-sample with 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 #11
Source File: SmsAuthenticationFilter.java    From SpringAll with 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);
}
 
Example #12
Source File: SmsCodeAuthenticationFilter.java    From Taroco with 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 #13
Source File: MobileTokenAuthenticationFilter.java    From Taroco with 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 #14
Source File: MobileAuthenticationFilter.java    From pig with 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 #15
Source File: AjaxAuthenticationFilter.java    From fw-cloud-framework with 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 #16
Source File: RefreshTokenProcessingFilter.java    From Groza with 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 #17
Source File: ControllerAdviceConfig.java    From guardedbox with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Exception handler for AuthenticationServiceException.
 *
 * @param e The AuthenticationServiceException.
 * @return Unauthorized (401) with no body.
 */
@ExceptionHandler
public ResponseEntity<?> exceptionHandler(
        AuthenticationServiceException e) {

    log.error(String.format(
            "Error during the request %s %s",
            request.getMethod(),
            request.getRequestURI()),
            e);

    session.invalidate();

    return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);

}
 
Example #18
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@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 #19
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@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 #20
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 6 votes vote down vote up
@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 #21
Source File: ZosmfServiceFacade.java    From api-layer with 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 #22
Source File: AbstractZosmfService.java    From api-layer with 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 #23
Source File: GatewayHealthIndicator.java    From api-layer with 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 #24
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@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 #25
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@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 #26
Source File: ZosmfAuthenticationProviderTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@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 #27
Source File: SmsAuthenticationFilter.java    From SpringAll with 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);
}
 
Example #28
Source File: SmsAuthenticationFilter.java    From SpringAll with 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);
}
 
Example #29
Source File: CustomAuthenticationFilter.java    From multitenancy with 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 File: SmsCodeAuthenticationFilter.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}