當前位置: 首頁>>代碼示例>>Java>>正文


Java UserDetails.getAuthorities方法代碼示例

本文整理匯總了Java中org.springframework.security.core.userdetails.UserDetails.getAuthorities方法的典型用法代碼示例。如果您正苦於以下問題:Java UserDetails.getAuthorities方法的具體用法?Java UserDetails.getAuthorities怎麽用?Java UserDetails.getAuthorities使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.springframework.security.core.userdetails.UserDetails的用法示例。


在下文中一共展示了UserDetails.getAuthorities方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: signInUser

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
public String signInUser(){

        boolean registered = userService.createUser(username, password);

        if(registered){

            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                    userDetails,
                    password,
                    userDetails.getAuthorities());

            authenticationManager.authenticate(token);

            if (token.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(token);
            }

            return "/index.jsf";
        } else {
            return "/signin.jsf?error=true";
        }
    }
 
開發者ID:arcuri82,項目名稱:testing_security_development_enterprise_systems,代碼行數:24,代碼來源:SignInController.java

示例2: autologin

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
/** {@inheritDoc} */
@Override
public void autologin(final String username, final String password) {
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

    authenticationManager.authenticate(usernamePasswordAuthenticationToken);

    if (usernamePasswordAuthenticationToken.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        logger.debug(String.format("Auto login %s successfully!", username));
    }
}
 
開發者ID:maugern,項目名稱:QRcode-factory,代碼行數:14,代碼來源:SecurityServiceImpl.java

示例3: doFilter

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = httpRequest.getHeader(this.tokenHeader);
    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(httpRequest));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
 
開發者ID:republique-et-canton-de-geneve,項目名稱:chvote-protocol-poc,代碼行數:19,代碼來源:JwtAuthenticationTokenFilter.java

示例4: authenticateAs

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
/**
 * Authenticate the user
 * @param userCredentials
 * @param setTimestamp true to set the lastSuccessfulLogin timestamp
 */
public void authenticateAs(YadaUserCredentials userCredentials, boolean setTimestamp) {
	UserDetails userDetails = createUserDetails(userCredentials);
	Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
	SecurityContextHolder.getContext().setAuthentication(auth);
	if (setTimestamp) {
		userCredentialsRepository.updateLoginTimestamp(userCredentials.getUsername().toLowerCase());
		userCredentialsRepository.resetFailedAttempts(userCredentials.getUsername().toLowerCase());
	}
}
 
開發者ID:xtianus,項目名稱:yadaframework,代碼行數:15,代碼來源:YadaUserDetailsService.java

示例5: setCurrentUser

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@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);
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:11,代碼來源:SpringSecurityUserContext.java

示例6: autoLogin

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@Override
public void autoLogin(String username, String password) {
    boolean isLogin = false;
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());

    authenticationManager.authenticate(usernamePasswordAuthenticationToken);

    if (usernamePasswordAuthenticationToken.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        isLogin = true;
    }

}
 
開發者ID:kuylim,項目名稱:spring-boot-security-vaadin,代碼行數:15,代碼來源:SecurityImpl.java

示例7: doFilterInternal

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    
	String authToken = request.getHeader(this.tokenHeader);

    if (!StringUtils.isEmpty(authToken) && SecurityContextHolder.getContext().getAuthentication() == null) {

    	try{
    		
    		HttpHeaders headers = new HttpHeaders();
    		headers.add("Authorization", authToken);
    		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    	
    		HttpEntity<String> entity = new HttpEntity<String>("", headers);
    		
    		ResponseEntity<String> responseEntity = 
    				restTemplate.exchange(
    						"http://AUTH-SERVICE/auth/current"
    						, HttpMethod.POST
    						, entity
    						, String.class);
        	
    		String jsonUserDetails = responseEntity.getBody();
            UserDetails userDetails = prepareUserDetails(jsonUserDetails);

            if (userDetails != null) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            
    	}catch(Exception e){
    		logger.error(e.getMessage());
    	}
    	
    }

    chain.doFilter(request, response);
}
 
開發者ID:satyendranit,項目名稱:pokemon,代碼行數:40,代碼來源:CommonAuthenticationTokenFilter.java

示例8: doFilterInternal

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String token = request.getHeader(tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    if (!tokenUtil.parseToken(token)){
        return;
    }
    String username = tokenUtil.getUsername();

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

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (!tokenUtil.isExpired()) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    filterChain.doFilter(request, response);
}
 
開發者ID:carycui,項目名稱:parkingcloud,代碼行數:29,代碼來源:JwtOncePerRequestFilter.java

示例9: doFilterInternal

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    String authToken = request.getHeader(this.tokenHeader);
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    String username = jwtTokenUtil.getUsernameFromToken(authToken);

    logger.info("checking authentication for user " + username);

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

        // It is not compelling necessary to load the use details from the database. You could also store the information
        // in the token and read it from it. It's up to you ;)
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

        // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
        // the database compellingly. Again it's up to you ;)
        if (jwtTokenUtil.validateToken(authToken, userDetails)) {
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            logger.info("authenticated user " + username + ", setting security context");
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    chain.doFilter(request, response);
}
 
開發者ID:jlmonteagudo,項目名稱:generator-spring-rest-jwt,代碼行數:28,代碼來源:_JwtAuthenticationTokenFilter.java

示例10: signInAdapter

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@Bean
public SignInAdapter signInAdapter(UserDetailsService userDetailsService) {
	RequestCache requestCache = new HttpSessionRequestCache();
	return (userId, connection, request) -> {
		UserDetails userDetails = userDetailsService.loadUserByUsername(userId);
		Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authentication);
		SavedRequest savedRequest = requestCache.getRequest(request.getNativeRequest(HttpServletRequest.class), request.getNativeResponse(HttpServletResponse.class));
		return savedRequest == null ? null : savedRequest.getRedirectUrl();
	};
}
 
開發者ID:codenergic,項目名稱:theskeleton,代碼行數:12,代碼來源:SocialConfig.java

示例11: setCurrentUser

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@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);
}
 
開發者ID:PacktPublishing,項目名稱:Spring-Security-Third-Edition,代碼行數:11,代碼來源:SpringSecurityUserContext.java

示例12: doFilterInternal

import org.springframework.security.core.userdetails.UserDetails; //導入方法依賴的package包/類
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    String authorization = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
    /**
     * Whenever the user wants to access a protected route or resource,
     * the user agent should send the JWT,
     * typically in the Authorization header using the Bearer schema.
     * The content of the header should look like the following:
     * Authorization: Bearer <token>
     * This is a stateless authentication mechanism as the user state is never saved in server memory.
     * The server's protected routes will check for a valid JWT in the Authorization header,
     * and if it's present, the user will be allowed to access protected resources.
     */
    // authToken.startsWith("Bearer ")
    // String authToken = header.substring(7);
    if (StringUtils.isBlank(authorization)) {
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        return;
    }

    try {
        String username = jwtTokenUtil.getUsernameFromToken(authorization);
        LOGGER.info("checking authentication for user:{},uri:{}", username, httpServletRequest.getRequestURI());

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {//服務器重啟的場景

            // It is not compelling necessary to load the use details from the database. You could also store the information
            // in the token and read it from it. It's up to you ;)
            //validateToken的邏輯中,就需要判斷username是否存在和過期時間
            //查出來UserDetails類型的數據是因為UsernamePasswordAuthenticationToken對象會使用
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // For simple validation it is completely sufficient to just check the token integrity. You don't have to call
            // the database compellingly. Again it's up to you ;)
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
            LOGGER.info("authenticated user {}, setting security context", username);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    } catch (Exception e) {
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        try (PrintWriter out = httpServletResponse.getWriter()) {
            out.write(JSON.toJSONString("unauthorized"));
            out.flush();
        }
    }

}
 
開發者ID:helloworldtang,項目名稱:spring-boot-jwt-jpa,代碼行數:52,代碼來源:JwtAuthenticationTokenFilter.java


注:本文中的org.springframework.security.core.userdetails.UserDetails.getAuthorities方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。