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


Java Authentication.isAuthenticated方法代碼示例

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


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

示例1: authenticationIsRequired

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
private boolean authenticationIsRequired(String username) {
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if (Objects.isNull(existingAuth) || !existingAuth.isAuthenticated()) {
        return true;
    }

    if (existingAuth instanceof UsernamePasswordAuthenticationToken
            && !existingAuth.getName().equals(username)) {
        return true;
    }

    if (existingAuth instanceof AnonymousAuthenticationToken) {
        return true;
    }

    return false;
}
 
開發者ID:revinate,項目名稱:grpc-spring-security-demo,代碼行數:18,代碼來源:BasicAuthenticationInterceptor.java

示例2: globalAttributes

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@ModelAttribute
public void globalAttributes(Model model) {
    Boolean isAllowedToUpdateMovieDB = true;
    String displayName = "Anonymous";

    if (facebookAppId != null && !facebookAppId.isEmpty()) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth instanceof OAuth2Authentication) {
            displayName = (String) ((LinkedHashMap) ((OAuth2Authentication) auth).getUserAuthentication().getDetails()).get("name");
            isAllowedToUpdateMovieDB = auth.isAuthenticated();
        } else {
            isAllowedToUpdateMovieDB = false;
        }
    }

    UserInfo userInfo = new UserInfo(displayName, isAllowedToUpdateMovieDB);
    model.addAttribute("userInfo", userInfo);
}
 
開發者ID:Microsoft,項目名稱:movie-db-java-on-azure,代碼行數:19,代碼來源:GlobalControllerAdvice.java

示例3: preHandle

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {

	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	boolean isAuthenticated;
	if (authentication != null) {
		isAuthenticated = authentication instanceof AnonymousAuthenticationToken ? false
				: authentication.isAuthenticated();
		if (isAuthenticated) {
			response.setContentType("text/plain");
			sendRedirect(request, response);
			return false; // no need to proceed with the chain as we already dealt with the response
		}
	}
	return true;
}
 
開發者ID:Azanx,項目名稱:Smart-Shopping,代碼行數:18,代碼來源:RedirectWhenAuthenticatedInterceptor.java

示例4: auditorAware

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Bean
public AuditorAware<String> auditorAware() {
    return new AuditorAware<String>() {
        @Override
        public String getCurrentAuditor() {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            if (authentication == null || !authentication.isAuthenticated()) {
                return null;
            }

            return authentication.getName();
        }
    };
}
 
開發者ID:weechang,項目名稱:Taroco,代碼行數:16,代碼來源:ApiGateWayApplication.java

示例5: doFilter

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    SecurityContext context = (SecurityContext) req.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY);
    if (context != null) {
        Authentication authentication = context.getAuthentication();
        if (authentication instanceof OAuth2Authentication && authentication.isAuthenticated()) {
            authentication = ((OAuth2Authentication) authentication).getUserAuthentication();
            if (authentication != null) {
                DiscordUserDetails details = SecurityUtils.getDetails(authentication);
                if (details != null) {
                    MDC.put("userId", details.getId());
                }
            }
        }
    }
    chain.doFilter(request, response);
}
 
開發者ID:GoldRenard,項目名稱:JuniperBotJ,代碼行數:19,代碼來源:InfoMdcFilter.java

示例6: logout

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@DeleteMapping(value = "/api/session", produces = CONTENT_TYPE)
public String logout() {
    logger.info("用戶登出: 正在檢測登入狀態");

    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        String username = authentication.getName();
        context.setAuthentication(null);
        if (!"anonymousUser".equals(username)) {
            logger.info("用戶登出: 用戶已成功登出, username={}", username);
            return booleanResult(true);
        } else {
            logger.info("用戶登出: 檢測到匿名用戶");
            return booleanResult(true);
        }
    } else {
        logger.info("用戶登出: 未檢測到已登入狀態");
        return booleanResult(false);
    }
}
 
開發者ID:mingzuozhibi,項目名稱:mzzb-server,代碼行數:22,代碼來源:SessionController.java

示例7: login

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public boolean login(String email, String password) {
	try {
		Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, password));
		if (authenticate.isAuthenticated()) {
			SecurityContextHolder.getContext().setAuthentication(authenticate);
			return true;
		}
	} catch (AuthenticationException e) {
	}
	return false;
}
 
開發者ID:zralock,項目名稱:CTUConference,代碼行數:13,代碼來源:AuthenticationServiceImpl.java

示例8: isUserLoggedIn

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
/**
 * Checks if is user logged in.
 *
 * @return true, if is user logged in
 */
protected static boolean isUserLoggedIn() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (null != authentication) {
        return (authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken));
    } else {
        return false;
    }

}
 
開發者ID:telstra,項目名稱:open-kilda,代碼行數:15,代碼來源:BaseController.java

示例9: getUser

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
private UserContext getUser(SecurityContext context) {
	if (context == null) return null;
	Authentication authentication = context.getAuthentication();
	if (authentication != null && authentication.isAuthenticated() && authentication.getPrincipal() instanceof UserContext)
		return (UserContext)authentication.getPrincipal();
	return null;
}
 
開發者ID:Jenner4S,項目名稱:unitimes,代碼行數:8,代碼來源:SessionsTag.java

示例10: authenticate

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
    Authentication authenticationResult = authenticationManager
        .authenticate(authentication);

    if (authenticationResult.isAuthenticated()) {
        // validates nonce because JWT is already valid
        if (authentication instanceof PoPAuthenticationToken) {
            PoPAuthenticationToken popAuthentication = (PoPAuthenticationToken) authentication;

            // starts validating nonce here
            String nonce = popAuthentication.getNonce();
            if (nonce == null) {
                throw new UnapprovedClientAuthenticationException(
                    "This request does not have a valid signed nonce");
            }

            String token = (String) popAuthentication.getPrincipal();

            System.out.println("access token:" + token);

            try {
                JWT jwt = JWTParser.parse(token);
                String publicKey = jwt.getJWTClaimsSet().getClaim("public_key").toString();
                JWK jwk = JWK.parse(publicKey);

                JWSObject jwsNonce = JWSObject.parse(nonce);
                JWSVerifier verifier = new RSASSAVerifier((RSAKey) jwk);
                if (!jwsNonce.verify(verifier)) {
                    throw new InvalidTokenException("Client hasn't possession of given token");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    return authenticationResult;
}
 
開發者ID:PacktPublishing,項目名稱:OAuth-2.0-Cookbook,代碼行數:42,代碼來源:PoPAuthenticationManager.java

示例11: isLogin

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
/**
 * 是否登錄
 * <p>
 * {@link Authentication#isAuthenticated()}
 *
 * @return <code>true</code> , 匿名用戶(未登錄)返回 <code>false</code>
 */
public static boolean isLogin () {
	Authentication authentication = getAuthentication();
	if ( authentication.getAuthorities().contains( ROLE_ANONYMOUS )
		|| ANONYMOUS_USER_PRINCIPAL.equals( authentication.getPrincipal() ) ) {
		return false;
	}
	return authentication.isAuthenticated();
}
 
開發者ID:yujunhao8831,項目名稱:spring-boot-start-current,代碼行數:16,代碼來源:ContextUtils.java

示例12: isLoggedIn

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
/**
 * Check if the current user is authenticated (logged in) not anonymously.
 * Use in thymeleaf with th:if="${@yadaWebUtil.loggedIn()}"
 * @return
 */
@Deprecated // use isLoggedIn() instead
public boolean loggedIn() {
	try {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth!=null && auth.isAuthenticated()) {
			Object principal = auth.getPrincipal();
			return (principal instanceof UserDetails);
		}
	} catch (Exception e) {
		log.error("Can't get Authentication object", e);
	}
	return false;
}
 
開發者ID:xtianus,項目名稱:yadaframework,代碼行數:19,代碼來源:YadaSecurityUtil.java

示例13: getValidAuthentication

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
protected Authentication getValidAuthentication() {
    SecurityContext ctx = getSecurityContext();
    if (ctx != null) {
        Authentication authc = ctx.getAuthentication();
        if (authc != null && !(authc instanceof AnonymousAuthenticationToken) && authc.isAuthenticated()) {
            return authc;
        }
    }
    return null;
}
 
開發者ID:juiser,項目名稱:juiser,代碼行數:11,代碼來源:SecurityContextUser.java

示例14: getTokenAuthentication

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
public static OAuth2Authentication getTokenAuthentication() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null && auth.isAuthenticated() && auth instanceof OAuth2Authentication) {
        return (OAuth2Authentication) auth;
    }
    return null;
}
 
開發者ID:GoldRenard,項目名稱:JuniperBotJ,代碼行數:8,代碼來源:SecurityUtils.java

示例15: login

import org.springframework.security.core.Authentication; //導入方法依賴的package包/類
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
    HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
    httpSessionSecurityContextRepository.loadContext(holder);

    try {
        // 使用提供的證書認證用戶
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN");
        Authentication auth = new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"), authorities);
        SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(auth));

        // 認證用戶
        if(!auth.isAuthenticated())
            throw new CredentialException("用戶不能夠被認證");
    } catch (Exception ex) {
        // 用戶不能夠被認證,重定向回登錄頁
        logger.info(ex);
        return "login";
    }

    // 從會話得到默認保存的請求
    DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
    // 為令牌請求生成認證參數Map
    Map<String, String> authParams = getAuthParameters(defaultSavedRequest);
    AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clientDetailsService).createAuthorizationRequest(authParams);
    authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"));
    model.addAttribute("authorizationRequest", authRequest);

    httpSessionSecurityContextRepository.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
    return "authorize";
}
 
開發者ID:chaokunyang,項目名稱:microservices-event-sourcing,代碼行數:32,代碼來源:LoginController.java


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