Java Code Examples for org.springframework.security.authentication.UsernamePasswordAuthenticationToken

The following examples show how to use org.springframework.security.authentication.UsernamePasswordAuthenticationToken. These examples are extracted from open source projects. 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 Project: tutorials   Source File: MockAuthenticationManager.java    License: MIT License 8 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{

    UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());

    if(userDetails == null || !passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword()))
    {
        throw new BadCredentialsException("Invalid username/password");
    }

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        authentication.getPrincipal().toString(),
        authentication.getCredentials().toString(),
        ROLES);

    return token;
}
 
Example 2
Source Project: HIS   Source File: SmsStaffServiceImpl.java    License: Apache License 2.0 8 votes vote down vote up
@Override
public String login(String username, String password) {
    String token = null;
    //密码需要客户端加密后传递
    try {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);//返回的是一个userDetails的实现类AdminUserDetails
        if(!passwordEncoder.matches(password,userDetails.getPassword())){  //password是从前端过来未经过编译的,而userDetails.getPassword()是从数据库中出来经过编译的
            throw new BadCredentialsException("密码不正确");
        }
        //创建一个新的token
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);  //在securityContext中添加该验证信息
        token = jwtTokenUtil.generateToken(userDetails);
        //updateLoginTimeByUsername(username);
        //insertLoginLog(username);
    } catch (AuthenticationException e) {
        LOGGER.warn("登录异常:{}", e.getMessage());
    }
    return token;
}
 
Example 3
Source Project: HIS   Source File: JwtAuthenticationTokenFilter.java    License: Apache License 2.0 8 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 4
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    if (authentication.getCredentials() == null) {
        logger.debug("Authentication failed: no credentials provided");
        throw new BadCredentialsException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", 
                        "Bad credentials"));
    }
    // Get the password submitted by the end user
    String presentedPassword = authentication.getCredentials().toString();

    // If the password stored in the database and the user submitted password do not
    // match, then signal a login error
    if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
        logger.debug("Authentication failed: password does not match stored value");
        throw new BadCredentialsException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", 
                        "Bad credentials"));
    }
}
 
Example 5
Source Project: sctalk   Source File: JwtAuthenticationTokenFilter.java    License: Apache License 2.0 7 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader("Authorization");
    String tokenHead = "Bearer ";
    if (authHeader != null && authHeader.startsWith(tokenHead)) {
        String authToken = authHeader.substring(tokenHead.length());
        String username = jwtTokenUtil.getUsernameFromToken(authToken);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 6
Source Project: codenjoy   Source File: IntegrationTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setup() {
    timer.resume();

    debug.setDebugEnable(false);

    smsProperties.setEnabled(false);
    verificationCode = "123456";

    mvc = MockMvcBuilders.webAppContextSetup(context).build();
    SecurityContextHolder.getContext()
            .setAuthentication(new UsernamePasswordAuthenticationToken(
                    config.getAdminLogin(),
                    config.getAdminPassword()
            ));
}
 
Example 7
@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;
}
 
Example 8
Source Project: HIS   Source File: JwtAuthenticationTokenFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 9
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    log.info("retrieveUser, for username={}", username);

    if (StringUtils.isEmpty(username)) {
        setHideUserNotFoundExceptions(false);//Setting this will cause UsernameNotFoundExceptions to be thrown instead of BadCredentialsException
        throw new UsernameNotFoundException("Enter your username.");
    }

    User user = userService.findUserByUsername(username);

    String givenPassword = (String) authentication.getCredentials();
    if (user == null || !user.getPassword().equals(givenPassword)) {
        throw new BadCredentialsException("Incorrect username or password.");
    }

    return user;
}
 
Example 10
@Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
//            updateLoginTimeByUsername(username);
            insertLoginLog(username);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }
 
Example 11
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 12
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 13
Source Project: datax-web   Source File: JWTAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
                                            HttpServletResponse response) throws AuthenticationException {

    // 从输入流中获取到登录的信息
    try {
        LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
        rememberMe.set(loginUser.getRememberMe());
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>())
        );
    } catch (IOException e) {
        logger.error("attemptAuthentication error :{}",e);
        return null;
    }
}
 
Example 14
public Authentication extractAuthentication(Map<String, ?> map) {
				
				if (map.containsKey(USERNAME)) {
					Object principal = map.get(USERNAME);
//					Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
					LoginAppUser loginUser = null;
					if (principal instanceof Map) {

						loginUser = BeanUtil.mapToBean((Map) principal, LoginAppUser.class, true);
						 
						Set<SysRole> roles = new HashSet<>();
						
						for(Iterator<SysRole> it = loginUser.getSysRoles().iterator(); it.hasNext();){
							SysRole role =  BeanUtil.mapToBean((Map) it.next() , SysRole.class, false);
							roles.add(role) ;
						}
						loginUser.setSysRoles(roles); 
					} 
					return new UsernamePasswordAuthenticationToken(loginUser, "N/A", loginUser.getAuthorities());
				}
				
				
				 
				return null;
			}
 
Example 15
Source Project: pentaho-kettle   Source File: UIEERepositoryDirectoryIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Logs in with given username.
 * 
 * @param username
 *          username of user
 * @param tenantId
 *          tenant to which this user belongs
 * @tenantAdmin true to add the tenant admin authority to the user's roles
 */
private void login( final String username, final ITenant tenant, String[] roles ) {
  StandaloneSession pentahoSession = new StandaloneSession( username );
  pentahoSession.setAuthenticated( tenant.getId(), username );
  PentahoSessionHolder.setSession( pentahoSession );
  pentahoSession.setAttribute( IPentahoSession.TENANT_ID_KEY, tenant.getId() );
  final String password = "password";

  List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

  if ( roles != null ) {
    for ( String roleName : roles ) {
      authorities.add( new SimpleGrantedAuthority( roleName ) );
    }
  }
  UserDetails userDetails = new User( username, password, true, true, true, true, authorities );
  Authentication auth = new UsernamePasswordAuthenticationToken( userDetails, password, authorities );
  PentahoSessionHolder.setSession( pentahoSession );
  // this line necessary for Spring Security's MethodSecurityInterceptor
  SecurityContextHolder.getContext().setAuthentication( auth );

  createUserHomeFolder( tenant, username );
}
 
Example 16
Source Project: tutorials   Source File: JWTFilterUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example 17
@Test
void testChangePasswordAuthenticatedUser() {
  String username = "MyUsername";
  String password = "MyPassword";

  SecurityContext securityContext = mock(SecurityContext.class);
  Authentication authentication =
      new UsernamePasswordAuthenticationToken(username, "MyCurrentPassword");
  when(securityContext.getAuthentication()).thenReturn(authentication);
  SecurityContextHolder.setContext(securityContext);

  User user = mock(User.class);
  when(userService.getUser(username)).thenReturn(user);
  passwordResetServiceImpl.changePasswordAuthenticatedUser(password);
  verify(user).setChangePassword(false);
  verify(userService).update(user);
}
 
Example 18
Source Project: mall-tiny   Source File: JwtAuthenticationTokenFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain chain) throws ServletException, IOException {
    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
        String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
        String username = jwtTokenUtil.getUserNameFromToken(authToken);
        LOGGER.info("checking username:{}", username);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                LOGGER.info("authenticated user:{}", username);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
    }
    chain.doFilter(request, response);
}
 
Example 19
Source Project: jhipster-online   Source File: JWTFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilterWrongScheme() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
 
Example 20
@RequestMapping (value = "/users/{userid}/cart/{cartid}/getcount",
   method = RequestMethod.GET)
public int countProductsInCart(Principal principal,
   @PathVariable (value = "userid") String userid,
   @PathVariable (value = "cartid") String cartid)
      throws ProductCartServiceException
{
   User user = (User)((UsernamePasswordAuthenticationToken) principal).
      getPrincipal();
   fr.gael.dhus.service.ProductCartService productCartService =
      ApplicationContextProvider.getBean(
         fr.gael.dhus.service.ProductCartService.class);

   try
   {
      return productCartService.countProductsInCart(user.getUUID());
   }
   catch (Exception e)
   {
      e.printStackTrace();
      throw new ProductCartServiceException(e.getMessage());
   }
}
 
Example 21
Source Project: training   Source File: TokenAuthenticationFilter.java    License: MIT License 6 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    try {
        String jwt = getJwtFromRequest(request);

        if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
            Long userId = tokenProvider.getUserIdFromToken(jwt);

            UserDetails userDetails = customUserDetailsService.loadUserById(userId);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    } catch (Exception ex) {
        logger.error("Could not set user authentication in security context", ex);
    }

    filterChain.doFilter(request, response);
}
 
Example 22
private void authenticate ()
{
   String name = "authenticatedUser";
   Set<GrantedAuthority> roles = new HashSet<> ();
   roles.add (new SimpleGrantedAuthority (Role.DOWNLOAD.getAuthority ()));
   roles.add (new SimpleGrantedAuthority (Role.SEARCH.getAuthority ()));
   roles.add (
         new SimpleGrantedAuthority (Role.USER_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 ());
}
 
Example 23
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

    String authToken = request.getHeader(this.tokenHeader);
    System.out.println(authToken);
    if (StringUtils.isNotEmpty(authToken) && authToken.startsWith(authTokenStart)) {
        authToken = authToken.substring(authTokenStart.length());
        log.info("请求" + request.getRequestURI() + "携带的token值:" + authToken);
        //如果在token过期之前触发接口,我们更新token过期时间,token值不变只更新过期时间
        //获取token生成时间
        Date createTokenDate = jwtTokenUtil.getCreatedDateFromToken(authToken);
        log.info("createTokenDate: " + createTokenDate);

    } else {
        // 不按规范,不允许通过验证
        authToken = null;
    }
    String username = jwtTokenUtil.getUsernameFromToken(authToken);
    log.info("JwtAuthenticationTokenFilter[doFilterInternal] checking authentication " + username);

    if (jwtTokenUtil.containToken(username, authToken) && username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        SecurityUser userDetail = jwtTokenUtil.getUserFromToken(authToken);
        if (jwtTokenUtil.validateToken(authToken, userDetail)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            log.info(String.format("Authenticated userDetail %s, setting security context", username));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }
    chain.doFilter(request, response);
}
 
Example 24
Source Project: flair-engine   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testgetCurrentUserJWT() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token"));
    SecurityContextHolder.setContext(securityContext);
    String jwt = SecurityUtils.getCurrentUserJWT();
    assertThat(jwt).isEqualTo("token");
}
 
Example 25
Source Project: java-tutorial   Source File: AuthUserService.java    License: MIT License 5 votes vote down vote up
/**
 * 登录获取token
 *
 * @param username
 * @param password
 * @return
 */
public String login(String username, String password) {
    UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
    Authentication authentication = authenticationManager.authenticate(upToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    UserDetails userDetails = loadUserByUsername(username);
    return jwtTokenUtil.generateToken(userDetails);
}
 
Example 26
Source Project: flair-engine   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousIsNotAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isFalse();
}
 
Example 27
Source Project: flair-engine   Source File: SecurityUtilsUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isTrue();
}
 
Example 28
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 29
@Override
public void setCurrentUser(CalendarUser user) {
    if (user == null) {
        throw new IllegalArgumentException("user cannot be null");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(),userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
}
 
Example 30
@Override
@Transactional(readOnly = true)
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    log.trace("retrieveUser()");
    log.debug("retrieving user: " + username);
    User user;
    try {
        user = this.read(username);
        if (user == null) {
            throw new Exception();
        }
    } catch (Exception e) {
        throw new UsernameNotFoundException("User " + username + " cannot be found");
    }

    String userName = user.getId();
    String pw = user.getPassword();
    List<Group> groups = this.identityService.createGroupQuery().groupMember(userName).groupType("security-role").list();
    List<String> groupStr = Lists.newArrayList();
    for (Group g : groups) {
        groupStr.add(g.getId());
    }
    Collection<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(Joiner.on(",").skipNulls().join(groupStr));
    boolean enabled = groupStr.contains("user");

    UserDetails userDetails = new org.springframework.security.core.userdetails.User(userName, pw, enabled, true, true, true, auths);
    log.debug("returning new userDetails: " + userDetails);
    return userDetails;
}