类org.springframework.security.authentication.AuthenticationServiceException源码实例Demo

下面列出了怎么用org.springframework.security.authentication.AuthenticationServiceException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: api-layer   文件: RestResponseHandler.java
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);
    }
}
 
@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);
	}
}
 
/**
 * 覆盖授权验证方法
 */
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);

}
 
@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));

}
 
@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);
}
 
源代码6 项目: cola   文件: OpenIdAuthenticationFilter.java
@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);
	}
}
 
源代码7 项目: cola   文件: AcAuthenticationFilter.java
@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);
	}
}
 
源代码8 项目: pre   文件: SmsCodeAuthenticationFilter.java
@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);
}
 
@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);
	}
}
 
/**
 * 覆盖授权验证方法
 */
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);

}
 
源代码11 项目: blog-sample   文件: SmsCodeAuthenticationFilter.java
@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);
}
 
源代码12 项目: blog-sample   文件: SmsCodeAuthenticationFilter.java
@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);
}
 
源代码13 项目: Taroco   文件: SmsCodeAuthenticationFilter.java
@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);
}
 
源代码14 项目: Taroco   文件: MobileTokenAuthenticationFilter.java
@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);
}
 
源代码15 项目: pig   文件: MobileAuthenticationFilter.java
@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);
}
 
@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);
}
 
源代码17 项目: Groza   文件: RefreshTokenProcessingFilter.java
@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));
}
 
@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);
}
 
@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);
}
 
@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);
}
 
@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);
}
 
源代码22 项目: api-layer   文件: ZosmfServiceFacade.java
/**
 * 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);
    }
}
 
源代码23 项目: api-layer   文件: AbstractZosmfService.java
/**
 * 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;
}
 
源代码24 项目: api-layer   文件: GatewayHealthIndicator.java
@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);
}
 
@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());
}
 
@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());
}
 
@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());
}
 
/**
 * 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);
}
 
源代码29 项目: multitenancy   文件: CustomAuthenticationFilter.java
@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);
}
 
源代码30 项目: SpringAll   文件: SmsAuthenticationFilter.java
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);
}
 
 类方法
 同包方法