当前位置: 首页>>代码示例>>Java>>正文


Java UsernamePasswordAuthenticationToken类代码示例

本文整理汇总了Java中org.springframework.security.authentication.UsernamePasswordAuthenticationToken的典型用法代码示例。如果您正苦于以下问题:Java UsernamePasswordAuthenticationToken类的具体用法?Java UsernamePasswordAuthenticationToken怎么用?Java UsernamePasswordAuthenticationToken使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


UsernamePasswordAuthenticationToken类属于org.springframework.security.authentication包,在下文中一共展示了UsernamePasswordAuthenticationToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getAuthentication

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
public Authentication getAuthentication(HttpServletRequest request) {
    String token = request.getHeader(HEADER_STRING);
    if (token != null) {
        // parse the token.
        String user = getUsername(token);

        String roles = getBody(token).get("roles", String.class);
        List<GrantedAuthority> grantedAuths =
                AuthorityUtils.commaSeparatedStringToAuthorityList(roles);

        return user != null ?
                new UsernamePasswordAuthenticationToken(user, null,
                        grantedAuths) :
                null;
    }
    return null;
}
 
开发者ID:Clcanny,项目名称:MicroServiceDemo,代码行数:18,代码来源:JwtTokenUtil.java

示例2: authenticate

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String email = token.getName();
    CalendarUser user = email == null ? null : calendarService.findUserByEmail(email);
    if(user == null) {
        throw new UsernameNotFoundException("Invalid username/password");
    }
    // Database Password already encrypted:
    String password = user.getPassword();

    boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password);

    if(!passwordsMatch) {
        throw new BadCredentialsException("Invalid username/password");
    }
    Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities);
    return usernamePasswordAuthenticationToken;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:21,代码来源:CalendarUserAuthenticationProvider.java

示例3: handleUsernameTokenPrincipal

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
protected void handleUsernameTokenPrincipal(UsernameTokenPrincipalCallback callback) throws IOException,
		UnsupportedCallbackException {
	UserDetails user = loadUserDetails(callback.getPrincipal().getName());
	WSUsernameTokenPrincipal principal = callback.getPrincipal();
	UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
			principal, principal.getPassword(), user.getAuthorities());
	if (logger.isDebugEnabled()) {
		logger.debug("Authentication success: " + authRequest.toString());
	}
	SecurityContextHolder.getContext().setAuthentication(authRequest);
	if (user instanceof IUser) {
		HttpSession session=ContextHolder.getHttpSession();
		session.setAttribute(ContextHolder.LOGIN_USER_SESSION_KEY, user);
		session.setAttribute(ContextHolder.USER_LOGIN_WAY_KEY,IWebservice.WS_LOGIN_WAY);
	}
}
 
开发者ID:bsteker,项目名称:bdf2,代码行数:18,代码来源:DigestPasswordValidationCallbackHandler.java

示例4: login

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@ApiOperation(value = "Login")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public boolean login(@RequestBody User user, HttpServletRequest request) {
    User u = this.userService.login(user.getUsername(), user.getPassword());
    if (u != null) {
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getPassword());

        // Authenticate the user
        Authentication authentication = authenticationManager.authenticate(authRequest);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        // Create a new session and add the security context.
        HttpSession session = request.getSession(true);
        session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
        return true;
    }
    return false;
}
 
开发者ID:bndynet,项目名称:web-framework-for-java,代码行数:21,代码来源:UserController.java

示例5: authorize

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@PostMapping("/authenticate")
@Timed
public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());

    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return ResponseEntity.ok(new JWTToken(jwt));
    } catch (AuthenticationException ae) {
        log.trace("Authentication exception trace: {}", ae);
        return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",
            ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
    }
}
 
开发者ID:mraible,项目名称:devoxxus-jhipster-microservices-demo,代码行数:21,代码来源:UserJWTController.java

示例6: authorize

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
@Timed
public ResponseEntity<?> authorize(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken =
        new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword());

    try {
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        boolean rememberMe = (loginDTO.isRememberMe() == null) ? false : loginDTO.isRememberMe();
        String jwt = tokenProvider.createToken(authentication, rememberMe);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
        return ResponseEntity.ok(new JWTToken(jwt));
    } catch (AuthenticationException exception) {
        return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",exception.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
    }
}
 
开发者ID:klask-io,项目名称:klask-io,代码行数:19,代码来源:UserJWTController.java

示例7: attemptAuthentication

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
	User creds = new ObjectMapper()
			.readValue(req.getInputStream(), User.class);
	
	List<Role> authorities = new ArrayList<>();
	authorities.add(Role.ROLE_MANAGER);
	authorities.add(Role.ROLE_EMPLOYE);
	authorities.add(Role.ROLE_ADMIN);
	
	return getAuthenticationManager().authenticate(
			new UsernamePasswordAuthenticationToken(
					creds.getMatricule(),
					creds.getPassword(),
					Collections.emptyList()
					)
			);
}
 
开发者ID:2017-d13,项目名称:attendance-manager-back,代码行数:19,代码来源:JWTLoginFilter.java

示例8: doFilterInternal

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String token = request.getHeader(AUTH_HEADER);
    if (token != null && token.startsWith(BEARER_PREFIX)) {
    	token = token.substring(7);
    }
    String username = jwtTokenUtil.getUsernameFromToken(token);

    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        
        if (jwtTokenUtil.tokenValido(token)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
 
开发者ID:m4rciosouza,项目名称:ponto-inteligente-api,代码行数:22,代码来源:JwtAuthenticationTokenFilter.java

示例9: loginHelp

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private MyUser loginHelp(MyUser user, String passwd, HttpSession session) {
	if (user.getUserId() != null) {
		String encryptedPassword;
		try {
			encryptedPassword = this.passwordEncryption.getEncryptedPassword(passwd, user.getSalt());
		} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
			return new MyUser();
		}
		if (user.getPassword().equals(encryptedPassword)) {				
			if(session != null) {	
				Authentication auth = 
						  new UsernamePasswordAuthenticationToken(user.getUserId(), user.getPassword(), user.getAuthorities());
				SecurityContextHolder.getContext().setAuthentication(auth);
				session.setAttribute(WebUtils.SECURITYCONTEXT, SecurityContextHolder.getContext());
			}
			user.setPassword("XXX");
			return user;
		}
	}
	session.invalidate();
	return new MyUser();
}
 
开发者ID:Angular2Guy,项目名称:AngularAndSpring,代码行数:23,代码来源:MyUserController.java

示例10: getAuthentication

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication getAuthentication(String token) {
  Claims claims = Jwts.parser()
    .setSigningKey(jwtProperties.getToken().getSecret())
    .parseClaimsJws(token)
    .getBody();

  Collection<? extends GrantedAuthority> authorities =
    Try.of(() ->
      Arrays.stream(claims.get(jwtProperties.getToken().getPayload().getAuthoritiesKey()).toString().split(","))
        .map(SimpleGrantedAuthority::new)
        .collect(Collectors.toList())
    ).recover(ex ->
      Collections.emptyList()
    ).get();

  User principal = new User(claims.getSubject(), "", authorities);

  return new UsernamePasswordAuthenticationToken(principal, "", authorities);
}
 
开发者ID:Cobrijani,项目名称:jwt-security-spring-boot-starter,代码行数:21,代码来源:JJWTTokenProvider.java

示例11: attemptAuthentication

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) {
        if(logger.isDebugEnabled()) {
            logger.debug("Authentication method not supported. Request method: " + request.getMethod());
        }
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }

    LoginRequest loginRequest = objectMapper.readValue(request.getReader(), LoginRequest.class);
    
    if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isBlank(loginRequest.getPassword())) {
        throw new AuthenticationServiceException("Username or Password not provided");
    }

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());

    return this.getAuthenticationManager().authenticate(token);
}
 
开发者ID:mjfcolas,项目名称:infotaf,代码行数:21,代码来源:AjaxLoginProcessingFilter.java

示例12: authenticate

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
private void authenticate ()
{
   String name = "userTest";
   Set<GrantedAuthority> roles = new HashSet<> ();
   roles.add (new SimpleGrantedAuthority (Role.DOWNLOAD.getAuthority ()));
   roles.add (new SimpleGrantedAuthority (Role.SEARCH.getAuthority ()));
   roles.add (
         new SimpleGrantedAuthority (Role.DATA_MANAGER.getAuthority ()));

   SandBoxUser user = new SandBoxUser (name, name, true, 0, roles);
   Authentication auth = new UsernamePasswordAuthenticationToken (
         user, user.getPassword (), roles);
   SecurityContextHolder.getContext ().setAuthentication (auth);

   logger.info ("userTest roles: " + auth.getAuthorities ());
}
 
开发者ID:SentinelDataHub,项目名称:dhus-core,代码行数:17,代码来源:TestCacheProductService.java

示例13: testDoFilterInternal

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Test
public void testDoFilterInternal() throws IOException, ServletException {
	JwtPayloadHelper payload = new JwtPayloadHelper()
			.withName(JwtAuthorizationFilter.ORG_NAME)
			.withOrgType(ORG_TYPE);

	request.addHeader("Authorization", JwtTestHelper.createJwt(payload));
	JwtAuthorizationFilter testJwtAuthFilter = new JwtAuthorizationFilter(authenticationManager);

	PowerMockito.mockStatic(SecurityContextHolder.class);
	SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class);

	PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext);

	testJwtAuthFilter.doFilterInternal(request, response, filterChain);

	verify(filterChain, times(1)).doFilter(any(MockHttpServletRequest.class), any(MockHttpServletResponse.class));
	verify(SecurityContextHolder.getContext(), times(1)).setAuthentication(any(UsernamePasswordAuthenticationToken.class));
}
 
开发者ID:CMSgov,项目名称:qpp-conversion-tool,代码行数:20,代码来源:JwtAuthorizationFilterTest.java

示例14: testDoFilterInternalWithInvalidOrgName

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
@Test
public void testDoFilterInternalWithInvalidOrgName() throws IOException, ServletException {
	JwtPayloadHelper payload = new JwtPayloadHelper()
			.withName("invalid-name")
			.withOrgType(ORG_TYPE);

	request.addHeader("Authorization", JwtTestHelper.createJwt(payload));
	JwtAuthorizationFilter testJwtAuthFilter = new JwtAuthorizationFilter(authenticationManager);

	PowerMockito.mockStatic(SecurityContextHolder.class);
	SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class);

	PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext);

	testJwtAuthFilter.doFilterInternal(request, response, filterChain);

	verify(filterChain, times(1)).doFilter(any(MockHttpServletRequest.class), any(MockHttpServletResponse.class));
	verify(SecurityContextHolder.getContext(), times(0)).setAuthentication(any(UsernamePasswordAuthenticationToken.class));
}
 
开发者ID:CMSgov,项目名称:qpp-conversion-tool,代码行数:20,代码来源:JwtAuthorizationFilterTest.java

示例15: signin

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; //导入依赖的package包/类
public String signin(String username, String password) {
  try {
    authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
    return jwtTokenProvider.createToken(username, userRepository.findByUsername(username).getRoles());
  } catch (AuthenticationException e) {
    throw new CustomException("Invalid username/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
  }
}
 
开发者ID:murraco,项目名称:spring-boot-jwt,代码行数:9,代码来源:UserService.java


注:本文中的org.springframework.security.authentication.UsernamePasswordAuthenticationToken类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。