org.springframework.security.authentication.AuthenticationManager类的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(15.6k)|赞(0)|评价(0)|浏览(139)

本文整理了Java中org.springframework.security.authentication.AuthenticationManager类的一些代码示例,展示了AuthenticationManager类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。AuthenticationManager类的具体详情如下:
包路径:org.springframework.security.authentication.AuthenticationManager
类名称:AuthenticationManager

AuthenticationManager介绍

[英]Processes an Authentication request.
[中]处理身份验证请求。

代码示例

代码示例来源:origin: weibocom/motan

@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public TokenTransfer authenticate(@RequestParam("username") String username, @RequestParam("password") String password) {
  UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
  Authentication authentication = authManager.authenticate(authenticationToken);
  SecurityContextHolder.getContext().setAuthentication(authentication);
  UserDetails userDetails = userDetailsService.loadUserByUsername(username);
  return new TokenTransfer(TokenUtils.createToken(userDetails));
}

代码示例来源:origin: spring-projects/spring-security-oauth

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {
  if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) {
    throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" });
  }
  String clientId = request.getParameter("client_id");
  String clientSecret = request.getParameter("client_secret");
  // If the request is already authenticated we can assume that this
  // filter is not needed
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if (authentication != null && authentication.isAuthenticated()) {
    return authentication;
  }
  if (clientId == null) {
    throw new BadCredentialsException("No client credentials presented");
  }
  if (clientSecret == null) {
    clientSecret = "";
  }
  clientId = clientId.trim();
  UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId,
      clientSecret);
  return this.getAuthenticationManager().authenticate(authRequest);
}

代码示例来源:origin: cloudfoundry/uaa

if (methods != null && !methods.contains(req.getMethod().toUpperCase())) {
    throw new BadCredentialsException("Credentials must be sent by (one of methods): " + methods);
  Authentication result = authenticationManager.authenticate(new AuthzAuthenticationRequest(loginInfo,
    new UaaAuthenticationDetails(req)));
  if (result.isAuthenticated()) {
    SecurityContextHolder.getContext().setAuthentication(result);
    ofNullable(successHandler).ifPresent(
      s -> s.setSavedAccountOptionCookie(req, res, result)
logger.debug("Authentication failed");
String acceptHeaderValue = req.getHeader("accept");
String clientId = req.getParameter("client_id");
if ("*/*; q=0.5, application/xml".equals(acceptHeaderValue) && "vmc".equals(clientId)) {
  buggyVmcAcceptHeader = true;

代码示例来源:origin: kbastani/spring-cloud-event-sourcing-example

new UsernamePasswordAuthenticationToken(request.getParameter("username"),
          request.getParameter("password"), authorities);
  SecurityContextHolder.getContext()
      .setAuthentication(authenticationManager.authenticate(auth));
  if(!authenticationManager.authenticate(auth).isAuthenticated())
    throw new CredentialException("User could not be authenticated");
DefaultSavedRequest defaultSavedRequest = ((DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"));
sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
model.addAttribute("authorizationRequest", authRequest);

代码示例来源:origin: geoserver/geoserver

throws IOException {
String usHeader = request.getHeader(userNameHeaderName);
String pwHeader = request.getHeader(passwordHeaderName);
    new UsernamePasswordAuthenticationToken(us, pw, new ArrayList<GrantedAuthority>());
Authentication auth = null;
try {
  auth = getSecurityManager().authenticationManager().authenticate(result);
} catch (ProviderNotFoundException e) {
  LOGGER.log(Level.WARNING, "couldn't to authenticate user:" + us);
for (GrantedAuthority grauth : auth.getAuthorities()) {
  roles.add((GeoServerRole) grauth);
    new UsernamePasswordAuthenticationToken(
        auth.getPrincipal(), auth.getCredentials(), roles);
newResult.setDetails(auth.getDetails());
SecurityContextHolder.getContext().setAuthentication(newResult);

代码示例来源:origin: jloisel/securing-rest-api-spring-security

@Override
public Authentication attemptAuthentication(
 final HttpServletRequest request,
 final HttpServletResponse response) {
 final String param = ofNullable(request.getHeader(AUTHORIZATION))
  .orElse(request.getParameter("t"));
 final String token = ofNullable(param)
  .map(value -> removeStart(value, BEARER))
  .map(String::trim)
  .orElseThrow(() -> new BadCredentialsException("Missing Authentication Token"));
 final Authentication auth = new UsernamePasswordAuthenticationToken(token, token);
 return getAuthenticationManager().authenticate(auth);
}

代码示例来源:origin: apache/nifi

private void authenticate(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
  String dnChain = null;
  try {
    final Authentication authenticationRequest = attemptAuthentication(request);
    if (authenticationRequest != null) {
      // log the request attempt - response details will be logged later
      log.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", authenticationRequest.toString(), request.getMethod(),
          request.getRequestURL().toString(), request.getRemoteAddr()));
      // attempt to authorize the user
      final Authentication authenticated = authenticationManager.authenticate(authenticationRequest);
      successfulAuthorization(request, response, authenticated);
    }
    // continue
    chain.doFilter(request, response);
  } catch (final AuthenticationException ae) {
    // invalid authentication - always error out
    unsuccessfulAuthorization(request, response, ae);
  }
}

代码示例来源:origin: spring-projects/spring-security

public void changePassword(String oldPassword, String newPassword) {
  Authentication currentUser = SecurityContextHolder.getContext()
      .getAuthentication();
  if (currentUser == null) {
    // This would indicate bad coding somewhere
    throw new AccessDeniedException(
        "Can't change password as no Authentication object found in context "
            + "for current user.");
  }
  String username = currentUser.getName();
  logger.debug("Changing password for user '" + username + "'");
  // If an authentication manager has been set, re-authenticate the user with the
  // supplied password.
  if (authenticationManager != null) {
    logger.debug("Reauthenticating user '" + username
        + "' for password change request.");
    authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
        username, oldPassword));
  }
  else {
    logger.debug("No authentication manager set. Password won't be re-checked.");
  }
  MutableUserDetails user = users.get(username);
  if (user == null) {
    throw new IllegalStateException("Current user doesn't exist in database.");
  }
  user.setPassword(newPassword);
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

String authorizationCode = request.getParameter("code");
HttpSession session = request.getSession();
String requestState = request.getParameter("state");
if (storedState == null || !storedState.equals(requestState)) {
  throw new AuthenticationServiceException("State parameter mismatch on return. Expected " + storedState + " got " + requestState);
        idToken, accessTokenValue, refreshTokenValue);
    Authentication authentication = this.getAuthenticationManager().authenticate(token);

代码示例来源:origin: ChinaSilence/any-video

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  String code = request.getParameter("code");
  String state = request.getParameter("state");
  GithubToken githubToken = this.getToken(code, state);
  if (githubToken != null){
    // 生成验证 authenticationToken
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(githubToken.getAccessToken(), githubToken.getScope());
    // 返回验证结果
    return this.getAuthenticationManager().authenticate(authRequest);
}
  return null;
}

代码示例来源:origin: cloudfoundry/uaa

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  if (!(authentication instanceof PasscodeAuthenticationFilter.ExpiringCodeAuthentication)) {
    return parent.authenticate(authentication);
  } else {
    PasscodeAuthenticationFilter.ExpiringCodeAuthentication expiringCodeAuthentication = (PasscodeAuthenticationFilter.ExpiringCodeAuthentication) authentication;
    if (methods != null && !methods.contains(expiringCodeAuthentication.getRequest().getMethod().toUpperCase())) {
      throw new BadCredentialsException("Credentials must be sent by (one of methods): " + methods);
      throw new BadCredentialsException("Invalid user.");
    Authentication result = new UsernamePasswordAuthenticationToken(
      principal,
      null,

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

/**
 * Pull the assertion out of the request and send it up to the auth manager for processing.
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  // check for appropriate parameters
  String assertionType = request.getParameter("client_assertion_type");
  String assertion = request.getParameter("client_assertion");
  try {
    JWT jwt = JWTParser.parse(assertion);
    String clientId = jwt.getJWTClaimsSet().getSubject();
    Authentication authRequest = new JWTBearerAssertionAuthenticationToken(jwt);
    return this.getAuthenticationManager().authenticate(authRequest);
  } catch (ParseException e) {
    throw new BadCredentialsException("Invalid JWT credential: " + assertion);
  }
}

代码示例来源:origin: cloudfoundry/uaa

protected Authentication attemptTokenAuthentication(HttpServletRequest request, HttpServletResponse response) {
  String grantType = request.getParameter("grant_type");
  logger.debug("Processing token user authentication for grant:"+grantType);
  Authentication authResult = null;
  if (GRANT_TYPE_PASSWORD.equals(grantType)) {
    Authentication credentials = extractCredentials(request);
    logger.debug("Authentication credentials found password grant for '" + credentials.getName() + "'");
    authResult = authenticationManager.authenticate(credentials);
    if (authResult != null && authResult.isAuthenticated() && authResult instanceof UaaAuthentication) {
      UaaAuthentication uaaAuthentication = (UaaAuthentication) authResult;
      if (uaaAuthentication.isRequiresPasswordChange()) {
  } else if (GRANT_TYPE_SAML2_BEARER.equals(grantType)) {
    logger.debug(GRANT_TYPE_SAML2_BEARER +" found. Attempting authentication with assertion");
    String assertion = request.getParameter("assertion");
    if (assertion != null && samlAuthenticationFilter != null) {
      logger.debug("Attempting SAML authentication for token endpoint.");
    String assertion = request.getParameter("assertion");
    if (assertion != null && xoAuthAuthenticationManager != null) {
      logger.debug("Attempting OIDC JWT authentication for token endpoint.");
  if (authResult != null && authResult.isAuthenticated()) {
    logger.debug("Authentication success: " + authResult.getName());
    return authResult;

代码示例来源:origin: spring-projects/spring-security-oauth

logger.debug("Clearing security context.");
    SecurityContextHolder.clearContext();
  request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
  if (authentication instanceof AbstractAuthenticationToken) {
    AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
    needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
  Authentication authResult = authenticationManager.authenticate(authentication);
  SecurityContextHolder.getContext().setAuthentication(authResult);
SecurityContextHolder.clearContext();

代码示例来源:origin: metatron-app/metatron-discovery

private void authenticateUser(String username, String password, HttpServletRequest request) {
 UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
 HttpSession session = request.getSession();
 authToken.setDetails(new WebAuthenticationDetails(request));
 Authentication authentication = authenticationManager.authenticate(authToken);
 SecurityContextHolder.getContext().setAuthentication(authentication);
 // creates context for that session.
 session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
 //set necessary details in session
 session.setAttribute("username", username);
 session.setAttribute("authorities", authentication.getAuthorities());
}

代码示例来源:origin: de.digitalcollections.commons/dc-commons-springsecurity

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
  throws AuthenticationException, IOException, ServletException {
 ObjectMapper mapper = new ObjectMapper();
 JsonNode root = mapper.readTree(request.getInputStream());
 String username = root.get("username").asText();
 String password = root.get("password").asText();
 UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
 return getAuthenticationManager().authenticate(token);
}

代码示例来源:origin: spring-projects/spring-security

ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
    .replaceQuery(null)
    this.authenticationManager.authenticate(authenticationRequest);
} catch (OAuth2AuthorizationException ex) {
  OAuth2Error error = ex.getError();
Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
String principalName = currentAuthentication != null ? currentAuthentication.getName() : "anonymousUser";

代码示例来源:origin: spring-projects/spring-security-oauth

logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
  Authentication authResult = authenticationManager.authenticate(credentials);
    logger.debug("Authentication success: " + authResult.getName());
  Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
  if (clientAuth == null) {
    throw new BadCredentialsException(
  map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());
  AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);
  SecurityContextHolder.getContext().setAuthentication(
      new OAuth2Authentication(storedOAuth2Request, authResult));
SecurityContextHolder.clearContext();

代码示例来源:origin: svlada/springboot-security-jwt

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    throws AuthenticationException, IOException, ServletException {
  String tokenPayload = request.getHeader(WebSecurityConfig.AUTHENTICATION_HEADER_NAME);
  RawAccessJwtToken token = new RawAccessJwtToken(tokenExtractor.extract(tokenPayload));
  return getAuthenticationManager().authenticate(new JwtAuthenticationToken(token));
}

代码示例来源:origin: wuyouzhuguli/SpringAll

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

相关文章

微信公众号

最新文章

更多

AuthenticationManager类方法