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

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

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

    Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
    String username = parameters.get("phone");
    String password = parameters.get("password");
    // Protect from downstream leaks of password
    parameters.remove("password");

    Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    try {
        userAuth = authenticationManager.authenticate(userAuth);
    } catch (AccountStatusException | BadCredentialsException ase) {
        //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
        throw new InvalidGrantException(ase.getMessage());
    } // If the username/password are wrong the spec says we should send 400/invalid grant

    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InvalidGrantException("Could not authenticate user: " + username);
    }

    return new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), userAuth);
}
 
源代码2 项目: cola   文件: OpenIdTokenGranter.java
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
	Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
	String openId = parameters.get("openid");
	String provider = parameters.get("provider");

	Authentication userAuth = new OpenIdAuthenticationToken(openId,provider);
	((AbstractAuthenticationToken) userAuth).setDetails(parameters);
	try {
		userAuth = authenticationManager.authenticate(userAuth);
	} catch (AccountStatusException | BadCredentialsException ase) {
		//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
		throw new InvalidGrantException(ase.getMessage());
	}
	if (userAuth == null || !userAuth.isAuthenticated()) {
		throw new InvalidGrantException("Could not authenticate user: " + openId);
	}

	OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
	return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
 
源代码3 项目: cola   文件: AcTokenGranter.java
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
	Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
	String authorizationCode = parameters.get("authorizationCode");
	String provider = parameters.get("provider");

	Authentication userAuth = new AcAuthenticationToken(authorizationCode, provider);
	((AbstractAuthenticationToken) userAuth).setDetails(parameters);
	try {
		userAuth = authenticationManager.authenticate(userAuth);
	} catch (AccountStatusException | BadCredentialsException ase) {
		//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
		throw new InvalidGrantException(ase.getMessage());
	}
	if (userAuth == null || !userAuth.isAuthenticated()) {
		throw new InvalidGrantException("Could not authenticate user: " + authorizationCode);
	}

	OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
	return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
 
源代码4 项目: cola   文件: SmsTokenGranter.java
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
	Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
	String phoneNumber = parameters.get("phoneNumber");
	String credential = parameters.get("credential");
	String token = parameters.get("token");

	Authentication userAuth = new SmsAuthenticationToken(phoneNumber, credential, token);
	((AbstractAuthenticationToken) userAuth).setDetails(parameters);
	try {
		userAuth = authenticationManager.authenticate(userAuth);
	} catch (AccountStatusException | BadCredentialsException ase) {
		//covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
		throw new InvalidGrantException(ase.getMessage());
	}
	if (userAuth == null || !userAuth.isAuthenticated()) {
		throw new InvalidGrantException("Could not authenticate user: " + phoneNumber);
	}

	OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
	return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
 
@Test
public void extractCustomAuthoritiesWithScopes() {
	TokenAuthenticationConverter tokenConverterCustom = new TokenAuthenticationConverter(
			new MyAuthoritiesExtractor(xsAppName, "cost-center",
					"country"));

	Jwt jwt = new JwtGenerator()
			.addScopes(scopeAdmin)
			.addAttribute("cost-center", new String[] { "0815" })
			.addAttribute("country", new String[] { "DE", "IL" })
			.getToken();

	AbstractAuthenticationToken authenticationToken = tokenConverterCustom.convert(jwt);
	assertThat(authenticationToken.getAuthorities().size(), is(4));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("ATTR:COST-CENTER=0815")));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("ATTR:COUNTRY=DE")));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("ATTR:COUNTRY=IL")));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeAdmin)));
}
 
@Test
public void authoritiesHaveLocalScopesWithoutAppIdPrefix() {
	String scopeWithNamespace = xsAppName + ".iot.Delete";
	String scopeWithOtherAppId = "anyAppId!t200." + xsAppName + ".Delete";

	Jwt jwt = new JwtGenerator()
			.addScopes(xsAppName + "." + scopeAdmin, scopeRead, scopeWithNamespace, scopeWithOtherAppId)
			.getToken();

	AbstractAuthenticationToken authenticationToken = tokenConverterLocalScopesOnly.convert(jwt);

	assertThat(authenticationToken.getAuthorities().size(), is(3));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeAdmin)));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("iot.Delete")));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority("Read")));
}
 
源代码7 项目: 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);
}
 
源代码8 项目: api-layer   文件: AbstractSecureContentFilter.java
/**
 * Extracts the token from the request and use the authentication manager to perform authentication.
 * Then set the currently authenticated principal and call the next filter in the chain.
 *
 * @param request     the http request
 * @param response    the http response
 * @param filterChain the filter chain
 * @throws ServletException a general exception
 * @throws IOException      a IO exception
 */
@Override
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
    Optional<AbstractAuthenticationToken> authenticationToken = extractContent(request);

    if (authenticationToken.isPresent()) {
        try {
            Authentication authentication = authenticationManager.authenticate(authenticationToken.get());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        } catch (AuthenticationException authenticationException) {
            failureHandler.onAuthenticationFailure(request, response, authenticationException);
        } catch (RuntimeException e) {
            resourceAccessExceptionHandler.handleException(request, response, e);
        }
    } else {
        filterChain.doFilter(request, response);
    }
}
 
源代码9 项目: attic-rave   文件: DefaultUserService.java
private SecurityContext createContext(final User user) {
    SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities()) {
        private static final long serialVersionUID = 1L;

        @Override
        public Object getCredentials() {
            return "N/A";
        }

        @Override
        public Object getPrincipal() {
            return user;
        }

        @Override
        public boolean isAuthenticated() {
            return true;
        }
    });
    return securityContext;
}
 
源代码10 项目: attic-rave   文件: DefaultUserServiceTest.java
@Test
public void getAuthenticatedUser_validUser() {
    final User authUser = new UserImpl(USER_ID);
    AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class);
    expect(auth.getPrincipal()).andReturn(authUser).anyTimes();
    replay(auth);

    SecurityContext context = new SecurityContextImpl();
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);

    User result = service.getAuthenticatedUser();

    assertThat(result, is(sameInstance(authUser)));
    verify(auth);
}
 
源代码11 项目: attic-rave   文件: RenderServiceIntegrationTest.java
@SuppressWarnings("unchecked")
@Before
public void setup() throws SQLException {
    restOperations = EasyMock.createNiceMock(RestOperations.class);
    EasyMock.expect(restOperations.postForObject(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class), EasyMock.anyObject(Class.class)))
            .andReturn(VALID_METADATA);
    EasyMock.replay(restOperations);

    //Replace the real restOperations instance with a mock -- otherwise the call for gadget metadata would fail since
    //we don't have a shindig server available to hit.
    ReflectionTestUtils.setField(metadataRepository, "restOperations", restOperations);

    //Setup a mock authenticated user
    final User authUser = new UserImpl(VALID_USER_ID, VALID_USER_NAME);
    AbstractAuthenticationToken auth = EasyMock.createNiceMock(AbstractAuthenticationToken.class);
    EasyMock.expect(auth.getPrincipal()).andReturn(authUser).anyTimes();
    EasyMock.replay(auth);

    SecurityContext context = new SecurityContextImpl();
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);
}
 
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    final String header = request.getHeader(TOKEN_HEADER_NAME);

    if (header == null || !header.startsWith(getHeaderPrefix())) {
        chain.doFilter(request, response);
        return;
    }

    AbstractAuthenticationToken authRequest = buildAuthentication(header);
    authRequest.setDetails(authenticationDetailsSource.buildDetails(request));

    final Authentication authResult;
    try {
        authResult = authenticationManager.authenticate(authRequest);
    } catch (AuthenticationException failed) {
        String errorMessage = failed.getMessage();
        SecurityContextHolder.clearContext();
        //response exception
        NodeMgrTools.responseString(response, errorMessage);
        return;
    }

    SecurityContextHolder.getContext().setAuthentication(authResult);

    chain.doFilter(request, response);
}
 
源代码13 项目: airsonic-advanced   文件: GlobalSecurityConfig.java
@EventListener
public void loginFailureListener(AbstractAuthenticationFailureEvent event) {
    if (event.getSource() instanceof AbstractAuthenticationToken) {
        AbstractAuthenticationToken token = (AbstractAuthenticationToken) event.getSource();
        Object details = token.getDetails();
        if (details instanceof WebAuthenticationDetails) {
            LOG.info("Login failed from [{}]", ((WebAuthenticationDetails) details).getRemoteAddress());
        }
    }
}
 
/**
 * get oauth2 authentication
 *
 * @param client       client detail
 * @param tokenRequest token request
 * @return oauth2 authentication
 */
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());

    UserDetails userDetails = apiBootOauthTokenGranter.loadByParameter(parameters);

    Authentication userAuth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);

    OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
    return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
 
源代码15 项目: api-boot   文件: DefaultApiBootOauthTokenGranter.java
/**
 * get oauth2 authentication
 *
 * @param client       client detail
 * @param tokenRequest token request
 * @return oauth2 authentication
 */
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());

    UserDetails userDetails = apiBootOauthTokenGranter.loadByParameter(parameters);

    Authentication userAuth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);

    OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
    return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
 
@Override
public void handle(HttpServletResponse response, Authentication authentication) {

       AuthType authType = (AuthType)authentication.getDetails();
       if (authType == AuthType.APIKEY) {
           Collection<UserRole> roles = new ArrayList<>();
           roles.add(UserRole.ROLE_API);

           AbstractAuthenticationToken authenticationWithAuthorities = new ApiTokenAuthenticationToken(authentication.getPrincipal(),
                   authentication.getCredentials(), createAuthorities(roles));
           authenticationWithAuthorities.setDetails(authentication.getDetails());
       }
       
}
 
源代码17 项目: oauth-server   文件: PrincipalServiceImpl.java
/**
 * details复制
 */
private void copyDetails(Authentication source, Authentication dest) {
    if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) {
        AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest;
        token.setDetails(source.getDetails());
    }
}
 
@Test
public void extractAuthoritiesWithoutScopes() {
	Jwt jwt = new JwtGenerator().getToken();

	AbstractAuthenticationToken authenticationToken = tokenConverterDefault.convert(jwt);
	assertThat(authenticationToken.getAuthorities().size(), is(0));
}
 
@Test
public void extractAuthoritiesIgnoresForeignScopes() {
	Jwt jwt = new JwtGenerator().addScopes(scopeAdmin, scopeOther, scopeRead).getToken();

	AbstractAuthenticationToken authenticationToken = tokenConverterLocalScopesOnly.convert(jwt);
	assertThat(authenticationToken.getAuthorities().size(), is(2));
	assertThat(authenticationToken.getAuthorities(), not(hasItem(new SimpleGrantedAuthority("Other"))));
}
 
@Test
public void extractAuthoritiesWithScopes() {
	Jwt jwt = new JwtGenerator().addScopes(scopeAdmin, scopeRead, scopeOther).getToken();

	AbstractAuthenticationToken authenticationToken = tokenConverterDefault.convert(jwt);
	assertThat(authenticationToken.getAuthorities().size(), is(3));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeRead)));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeAdmin)));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeOther)));
}
 
@Test
public void extractAuthoritiesWithScopesOAuth2Authentication() {
	Jwt jwt = new JwtGenerator().addScopes(scopeAdmin, scopeRead, scopeOther).getToken();

	AbstractAuthenticationToken authenticationToken = tokenConverterOauth2.convert(jwt);
	assertThat(authenticationToken.getAuthorities().size(), is(3));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeRead)));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeAdmin)));
	assertThat(authenticationToken.getAuthorities(), hasItem(new SimpleGrantedAuthority(scopeOther)));

	assertTrue(authenticationToken instanceof OAuth2Authentication);
	assertThat(((OAuth2Authentication) authenticationToken).getOAuth2Request().getScope(), hasItem(scopeRead));
}
 
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  String doAsUserName = request.getParameter("doAs");
  final List<GrantedAuthority> authorities = RoleDao.createDefaultAuthorities();
  final UserDetails principal = new User(doAsUserName, "", authorities);
  final AbstractAuthenticationToken finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", authorities);
  WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request);
  finalAuthentication.setDetails(webDetails);
  SecurityContextHolder.getContext().setAuthentication(finalAuthentication);
  logger.info("Logged into Log Search User as doAsUser = {}", doAsUserName);
  return finalAuthentication;
}
 
@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request,
    HttpServletResponse response) throws IOException, ServletException {
  logger.debug("LogsearchKRBAuthenticationFilter private filter");
  String userName = getUsernameFromResponse(response);
  if (StringUtils.isNotEmpty(userName)) {
    Authentication existingAuth = SecurityContextHolder.getContext()
        .getAuthentication();
    if (existingAuth == null || !existingAuth.isAuthenticated()) {
      // --------------------------- To Create Logsearch Session--------------------------------------
      // if we get the userName from the token then log into Logsearch using the same user
      final List<GrantedAuthority> grantedAuths = new ArrayList<>();
      grantedAuths.add(new SimpleGrantedAuthority(DEFAULT_USER_ROLE));
      final UserDetails principal = new User(userName, "", grantedAuths);
      final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
          principal, "", grantedAuths);
      WebAuthenticationDetails webDetails = new WebAuthenticationDetails(
          request);
      ((AbstractAuthenticationToken) finalAuthentication)
          .setDetails(webDetails);
      Authentication authentication = this
          .authenticate(finalAuthentication);
      authentication = getGrantedAuthority(authentication);
      SecurityContextHolder.getContext().setAuthentication(authentication);
      request.getSession(true).setAttribute("SPRING_SECURITY_CONTEXT",
          SecurityContextHolder.getContext());
      request.setAttribute("spnegoEnabled", true);
      logger.info("Logged into Logsearch as = " + userName);
      filterChain.doFilter(request, response);
    } else {
      try {
        super.doFilter(filterChain, request, response);
      } catch (Exception e) {
        logger.error("Error LogsearchKRBAuthenticationFilter : " + e.getMessage());
      }
    }
  } else {
    filterChain.doFilter(request, response);
  }
}
 
@Test
public void testSupports() {
    ZosmfAuthenticationProvider mock = new ZosmfAuthenticationProvider(null, null);

    assertTrue(mock.supports(UsernamePasswordAuthenticationToken.class));
    assertFalse(mock.supports(Object.class));
    assertFalse(mock.supports(AbstractAuthenticationToken.class));
    assertFalse(mock.supports(JaasAuthenticationToken.class));
    assertFalse(mock.supports(null));
}
 
源代码25 项目: api-layer   文件: CookieContentFilter.java
/**
 * Extract the valid JWT token from the cookies
 *
 * @param request the http request
 * @return the {@link TokenAuthentication} object containing username and valid JWT token
 */
public Optional<AbstractAuthenticationToken> extractContent(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return Optional.empty();
    }

    return Arrays.stream(cookies)
        .filter(cookie -> cookie.getName().equals(authConfigurationProperties.getCookieProperties().getCookieName()))
        .filter(cookie -> !cookie.getValue().isEmpty())
        .findFirst()
        .map(cookie -> new TokenAuthentication(cookie.getValue()));
}
 
源代码26 项目: api-layer   文件: BasicContentFilter.java
/**
 * Extract credentials from the authorization header in the request and decode them
 *
 * @param request the http request
 * @return the decoded credentials
 */
public Optional<AbstractAuthenticationToken> extractContent(HttpServletRequest request) {
    return Optional.ofNullable(
        request.getHeader(HttpHeaders.AUTHORIZATION)
    ).filter(
        header -> header.startsWith(ApimlConstants.BASIC_AUTHENTICATION_PREFIX)
    ).map(
        header -> header.replaceFirst(ApimlConstants.BASIC_AUTHENTICATION_PREFIX, "").trim()
    )
        .filter(base64Credentials -> !base64Credentials.isEmpty())
        .map(this::mapBase64Credentials);
}
 
源代码27 项目: api-layer   文件: CookieContentFilterTest.java
@Test
public void shouldReturnEmptyIfCookieValueIsEmpty() {
    Cookie cookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), "");
    request.setCookies(cookie);

    Optional<AbstractAuthenticationToken> content = cookieContentFilter.extractContent(request);

    assertFalse(content.isPresent());
}
 
源代码28 项目: api-layer   文件: BasicContentFilterTest.java
@Test
public void extractContentFromRequestWithValidBasicAuth() {
    request.addHeader(HttpHeaders.AUTHORIZATION, BASIC_AUTH);
    Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request);

    assertTrue(token.isPresent());
    assertEquals("user", token.get().getPrincipal());
    assertEquals("password", token.get().getCredentials().toString());
}
 
源代码29 项目: api-layer   文件: BasicContentFilterTest.java
@Test
public void extractContentFromRequestWithNonsenseBasicAuth() {
    request.addHeader(HttpHeaders.AUTHORIZATION, "Basic dXNlG4m3oFthR0n3syZA==");
    Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request);

    assertTrue(token.isPresent());
    assertNull(token.get().getPrincipal());
    assertNull(token.get().getCredentials());
}
 
源代码30 项目: api-layer   文件: BasicContentFilterTest.java
@Test
public void extractContentFromRequestWithNonsense() {
    request.addHeader(HttpHeaders.AUTHORIZATION, "Duck");
    Optional<AbstractAuthenticationToken> token = basicContentFilter.extractContent(request);

    assertFalse(token.isPresent());
}
 
 类方法
 同包方法