@GetMapping("/article/{id}")
public String details(Model model, @PathVariable Integer id) {
if (!this.articleRepository.exists(id)) {
return "redirect:/";
}
if (!(SecurityContextHolder.getContext().getAuthentication()
instanceof AnonymousAuthenticationToken)) {
UserDetails user = (UserDetails) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
User userEntity = this.userRepository.findByEmail(user.getUsername());
model.addAttribute("user", userEntity);
}
Article article = this.articleRepository.findOne(id);
model.addAttribute("article", article);
model.addAttribute("view", "article/details");
return "base-layout";
}
java类org.springframework.security.authentication.AnonymousAuthenticationToken的实例源码
ArticleController.java 文件源码
项目:KPBlog
阅读 27
收藏 0
点赞 0
评论 0
RedirectWhenAuthenticatedInterceptor.java 文件源码
项目:Smart-Shopping
阅读 25
收藏 0
点赞 0
评论 0
@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;
}
SecurityUtil.java 文件源码
项目:sns-todo
阅读 55
收藏 0
点赞 0
评论 0
public static String getUserName() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof UsernamePasswordAuthenticationToken) {
return authentication.getName();
}
if (authentication instanceof OAuth2Authentication) {
log.info("third part login.authentication:{}, user {},from {}", authentication, authentication.getName(), NetworkUtil.getRemoteIp());
return authentication.getName();
}
if (authentication instanceof AnonymousAuthenticationToken) {
log.warn(" user {} not login,from {}", authentication.getName(), NetworkUtil.getRemoteIp());
return authentication.getName();
}
log.warn("{} isAuthenticated():{},name:{},details:{}", Flag.BizLogFlag.WARN_CHECK, authentication.isAuthenticated(), authentication.getName(), authentication.getDetails());
throw new ApiBizException(GlobalCode.UNKNOWN);
}
PostServiceImpl.java 文件源码
项目:nixmash-blog
阅读 27
收藏 0
点赞 0
评论 0
@Override
public boolean canUpdatePost(Authentication authentication, Long postId) {
if (authentication instanceof AnonymousAuthenticationToken)
return false;
CurrentUser currentUser = (CurrentUser) authentication.getPrincipal();
Post post = null;
try {
post = getPostById(postId);
} catch (PostNotFoundException e) {
logger.error("Post not found for PostId {} ", postId);
return false;
}
Long postUserId = post.getUserId();
return currentUser.getId().equals(postUserId);
}
BasicAuthenticationInterceptor.java 文件源码
项目:grpc-spring-security-demo
阅读 23
收藏 0
点赞 0
评论 0
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;
}
AnonymousAuthenticationInterceptor.java 文件源码
项目:grpc-spring-security-demo
阅读 29
收藏 0
点赞 0
评论 0
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
if (Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken(key,
"anonymousUser", Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
log.debug("Populated SecurityContextHolder with anonymous token: {}",
SecurityContextHolder.getContext().getAuthentication());
} else {
log.debug("SecurityContextHolder not populated with anonymous token, as it already contained: {}",
SecurityContextHolder.getContext().getAuthentication());
}
return next.startCall(call, headers);
}
SecurityController.java 文件源码
项目:spring-cloud-dashboard
阅读 40
收藏 0
点赞 0
评论 0
/**
* Return security information. E.g. is security enabled? Which user do you represent?
*/
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public SecurityInfoResource getSecurityInfo() {
final boolean authenticationEnabled = securityProperties.getBasic().isEnabled();
final SecurityInfoResource securityInfo = new SecurityInfoResource();
securityInfo.setAuthenticationEnabled(authenticationEnabled);
securityInfo.add(ControllerLinkBuilder.linkTo(SecurityController.class).withSelfRel());
if (authenticationEnabled && SecurityContextHolder.getContext() != null) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
securityInfo.setAuthenticated(authentication.isAuthenticated());
securityInfo.setUsername(authentication.getName());
}
}
return securityInfo;
}
MarketplaceDAO.java 文件源码
项目:dawn-marketplace-server
阅读 26
收藏 0
点赞 0
评论 0
/**
* Tests whether or not the current user have access to edit the solution
* with the given identifier. The user must be an administrator or own the
* solution.
*
* @param identifier
* the identifier of the solution
* @return <code>true</code> if editable
*/
public boolean canEdit(Long identifier) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
return false;
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
return true;
}
}
// new solution
if (identifier == null) {
return true;
}
Account account = accountRepository.findOne(authentication.getName());
Account a = accountRepository.findAccountBySolutionId(identifier);
if (account.getUsername().equals(a.getUsername())) {
return true;
}
return false;
}
ExternalMooseDataCardImportApiResource.java 文件源码
项目:oma-riista-web
阅读 30
收藏 0
点赞 0
评论 0
@CacheControl(policy = CachePolicy.NO_CACHE)
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> importMooseDataCard(
@RequestParam final MultipartFile xmlFile, @RequestParam final MultipartFile pdfFile) {
LOG.debug("Moose data card upload request received via anonymous API");
final SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(new AnonymousAuthenticationToken(
"key", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
if (LOG.isDebugEnabled()) {
LOG.debug("Populated SecurityContextHolder with anonymous token: '" + sc.getAuthentication() + "'");
}
try {
return ResponseEntity.ok(toMap(importFeature.importMooseDataCardWithSpecialPrivilege(xmlFile, pdfFile)));
} catch (final MooseDataCardImportException e) {
return ResponseEntity.badRequest().body(toMap(e.getMessages()));
}
}
UserController.java 文件源码
项目:web-ui
阅读 35
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
if (!model.containsAttribute("login")) {
model.addAttribute("login", new AuthenticationRequest());
}
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
try {
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
User user = userService.getUser(currentUserName);
model.addAttribute("user", user);
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
}
return "index";
}
AccountsController.java 文件源码
项目:web-ui
阅读 36
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/accounts", method = RequestMethod.GET)
public String accounts(Model model) {
logger.debug("/accounts");
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("accounts: User logged in: " + currentUserName);
try {
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving accounts: " + e.getMessage());
model.addAttribute("accountsRetrievalError",e.getMessage());
}
}
return "accounts";
}
TradeController.java 文件源码
项目:web-ui
阅读 26
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/trade", method = RequestMethod.GET)
public String showTrade(Model model) {
logger.debug("/trade.GET");
//model.addAttribute("marketSummary", marketService.getMarketSummary());
model.addAttribute("search", new Search());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
model.addAttribute("order", new Order());
try {
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
}
return "trade";
}
PortfolioController.java 文件源码
项目:web-ui
阅读 28
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
logger.debug("/portfolio");
model.addAttribute("marketSummary", summaryService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("portfolio: User logged in: " + currentUserName);
//TODO: add account summary.
try {
model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
model.addAttribute("accounts",accountService.getAccounts(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving portfolfio: " + e.getMessage());
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
model.addAttribute("order", new Order());
}
return "portfolio";
}
FiatAuthenticationFilter.java 文件源码
项目:fiat
阅读 26
收藏 0
点赞 0
评论 0
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Authentication auth = AuthenticatedRequest
.getSpinnakerUser()
.map(username -> (Authentication) new PreAuthenticatedAuthenticationToken(username,
null,
new ArrayList<>()))
.orElseGet(() -> new AnonymousAuthenticationToken(
"anonymous",
"anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")
));
val ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(auth);
SecurityContextHolder.setContext(ctx);
log.debug("Set SecurityContext to user: {}", auth.getPrincipal().toString());
chain.doFilter(request, response);
}
SSOController.java 文件源码
项目:spring-tsers-auth
阅读 33
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/idpSelection", method = RequestMethod.GET)
public String idpSelection(HttpServletRequest request, Model model) {
if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) {
LOG.warn("The current user is already logged.");
return "redirect:/landing";
} else {
if (isForwarded(request)) {
Set<String> idps = metadata.getIDPEntityNames();
for (String idp : idps)
LOG.info("Configured Identity Provider for SSO: " + idp);
model.addAttribute("idps", idps);
return "saml/idpselection";
} else {
LOG.warn("Direct accesses to '/idpSelection' route are not allowed");
return "redirect:/";
}
}
}
AdminController.java 文件源码
项目:helicalinsight
阅读 38
收藏 0
点赞 0
评论 0
private String whenUserHasValidSession(Authentication authentication, HttpSession session) {
String redirectUrl = null;
if (!(authentication instanceof AnonymousAuthenticationToken)) {
List<String> userRoles = AuthenticationUtils.getUserRoles();
if (userRoles.contains(this.namesConfigurer.getRoleAdmin())) {
String roleAdmin = namesConfigurer.getRoleAdmin();
session.setAttribute("superAdminRole", roleService.findRoleByName(roleAdmin));
redirectUrl = "./admin.html";
} else if (userRoles.contains(this.namesConfigurer.getRoleUser())) {
redirectUrl = "./hi.html";
} else {
redirectUrl = "./welcome.html";
}
}
return redirectUrl;
}
MidpointRestSecurityQuestionsAuthenticator.java 文件源码
项目:engerek
阅读 25
收藏 0
点赞 0
评论 0
private List<SecurityQuestionDefinitionType> getQuestions(PrismObject<UserType> user) {
return getSecurityEnforcer().runPrivileged(new Producer<List<SecurityQuestionDefinitionType>>() {
@Override
public List<SecurityQuestionDefinitionType> run() {
Task task = getTaskManager().createTaskInstance("Search user by name");
OperationResult result = task.getResult();
SecurityPolicyType securityPolicyType = null;
try {
SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("rest_sec_q_auth", "REST", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
securityPolicyType = modelInteractionService.getSecurityPolicy(user, task, result);
} catch (ObjectNotFoundException | SchemaException e) {
return null;
} finally {
SecurityContextHolder.getContext().setAuthentication(null);
}
if (securityPolicyType.getCredentials() != null && securityPolicyType.getCredentials().getSecurityQuestions() != null){
return securityPolicyType.getCredentials().getSecurityQuestions().getQuestion();
}
return null;
}
});
}
UserController.java 文件源码
项目:springBootTrader-aos
阅读 32
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHome(Model model) {
if (!model.containsAttribute("login")) {
model.addAttribute("login", new AuthenticationRequest());
}
model.addAttribute("marketSummary", marketService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
try {
model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
model.addAttribute("account",accountService.getAccount(currentUserName));
}
return "index";
}
TradeController.java 文件源码
项目:springBootTrader-aos
阅读 29
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/trade", method = RequestMethod.GET)
public String showTrade(Model model) {
logger.debug("/trade.GET");
//model.addAttribute("marketSummary", marketService.getMarketSummary());
model.addAttribute("search", new Search());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("User logged in: " + currentUserName);
model.addAttribute("order", new Order());
//TODO: add account summary?
try {
model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
}
return "trade";
}
TradeController.java 文件源码
项目:springBootTrader-aos
阅读 26
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/order", method = RequestMethod.POST)
public String buy(Model model, @ModelAttribute("order") Order order) {
model.addAttribute("search", new Search());
// buy the order after setting attributes not set by the UI.
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("/order ORDER: " + order);
order.setAccountId(currentUserName);
order.setCompletionDate(new Date());
Order result = marketService.sendOrder(order);
model.addAttribute("savedOrder", result);
model.addAttribute("order", new Order());
try {
model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
} else {
//should never get here!!!
}
return "trade";
}
PortfolioController.java 文件源码
项目:springBootTrader-aos
阅读 26
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/portfolio", method = RequestMethod.GET)
public String portfolio(Model model) {
logger.debug("/portfolio");
model.addAttribute("marketSummary", marketService.getMarketSummary());
//check if user is logged in!
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
String currentUserName = authentication.getName();
logger.debug("portfolio: User logged in: " + currentUserName);
//TODO: add account summary.
try {
model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
} catch (HttpServerErrorException e) {
logger.debug("error retrieving portfolfio: " + e.getMessage());
model.addAttribute("portfolioRetrievalError",e.getMessage());
}
model.addAttribute("order", new Order());
}
return "portfolio";
}
SecurityHelper.java 文件源码
项目:NetLicensing-Gateway
阅读 32
收藏 0
点赞 0
评论 0
public Context getContext() {
final Context context = new Context();
context.setBaseUrl(nlicBaseUrl);
context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
context.setObject(RestProvider.Configuration.class, new GWClientConfiguration());
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
if (authentication instanceof AnonymousAuthenticationToken) {
// TODO(2K): handle missing authentication (no cases so far)
context.setUsername("");
context.setPassword("");
} else {
context.setUsername(authentication.getPrincipal().toString());
context.setPassword(authentication.getCredentials().toString());
}
}
return context;
}
RootController.java 文件源码
项目:java-spring-jspx-hibernate-template
阅读 49
收藏 0
点赞 0
评论 0
@RequestMapping(value = Constants.Url.LOGIN, method = RequestMethod.GET)
public String showLoginPage(@RequestParam(value = Constants.RequestParam.ERROR, required = false) Boolean error,
@RequestParam(value = Constants.RequestParam.LOGOUT, required = false) Boolean logout,
Model model) {
SecurityContext securityContext = SecurityContextHolder.getContext();
if (securityContext != null) {
Authentication authentication = securityContext.getAuthentication();
if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
return Constants.Url.REDIRECT + Constants.Url.ROOT;
}
}
if (error != null) {
model.addAttribute(Constants.ModelAttribute.ERROR, Constants.Messages.PAGE_LOGIN_ERROR_INVALID_USERNAME_AND_PASSWORD);
}
if (logout != null) {
model.addAttribute(Constants.ModelAttribute.LOGOUT, Constants.Messages.PAGE_LOGIN_MESSAGE_LOGOUT);
}
return Constants.View.LOGIN;
}
AbstractCoreSession.java 文件源码
项目:owsi-core-parent
阅读 31
收藏 0
点赞 0
评论 0
/**
* @see AbstractCoreSession#authenticate(String, String)
*/
public void signInAs(String username) throws UsernameNotFoundException {
// on charge l'utilisateur
// on le passe dans une méthode surchargeable -> implémentation par défaut à faire
// Sitra -> revoir l'implémentation par défaut
if (!hasSignInAsPermissions(getUser(), userService.getByUserName(username))) {
throw new SecurityException("L'utilisateur n'a pas les permissions nécessaires");
}
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
RunAsUserToken token = new RunAsUserToken(defaultJpaSecurityConfig.getRunAsKey(),
userDetails, "runAs", userDetails.getAuthorities(), null);
// On garde l'authentification de l'utilisateur pour pouvoir lui proposer de se reconnecter.
Authentication previousAuthentication = SecurityContextHolder.getContext().getAuthentication();
if (!(previousAuthentication instanceof AnonymousAuthenticationToken)) {
originalAuthentication = previousAuthentication;
}
signOut();
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
doInitializeSession();
bind();
signIn(true);
}
PermissionAcquireFilter.java 文件源码
项目:data-acquisition
阅读 26
收藏 0
点赞 0
评论 0
@Override protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse httpServletResponse, FilterChain filterChain)
throws ServletException, IOException {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String authHeader = null;
if(authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
authHeader = tokenRetriever.getAuthToken(authentication);
}
if(authHeader == null) {
LOGGER.debug("Request has no authorization header.");
httpServletResponse.sendError(401, "Unauthorized.");
}
else {
UUID[] ids = authorization.getAccessibleOrgs(request).stream()
.map(org -> org.getOrganization().getGuid()).toArray(size -> new UUID[size]);
request.setAttribute(ACCESSIBLE_ORGS, ids);
if (ids.length > 0) {
filterChain.doFilter(request, httpServletResponse);
} else {
LOGGER.debug("User access denied.");
httpServletResponse.sendError(403, "Can't access this organization.");
}
}
}
MainController.java 文件源码
项目:hotel_shop
阅读 32
收藏 0
点赞 0
评论 0
/**
* Accesss denied.
*
* @return the model and view
*/
@RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied(HttpServletRequest request) {
ModelAndView model = new ModelAndView();
// check if user is login
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
System.out.println(userDetail);
model.addObject("username", userDetail.getUsername());
}
model.setViewName(checkName("403", request));
return model;
}
MainController.java 文件源码
项目:hotel_shop
阅读 37
收藏 0
点赞 0
评论 0
/**
* Not found.
*
* @return the model and view
*/
@RequestMapping(value = "/404", method = RequestMethod.GET)
public ModelAndView notFound(HttpServletRequest request) {
ModelAndView model = new ModelAndView();
// check if user is login
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
System.out.println(userDetail);
model.addObject("username", userDetail.getUsername());
}
model.setViewName(checkName("404", request));
return model;
}
LoginPage.java 文件源码
项目:webanno
阅读 31
收藏 0
点赞 0
评论 0
private void redirectIfAlreadyLoggedIn()
{
// If we are already logged in, redirect to the welcome page. This tries to a void a
// situation where the user tries to access the login page directly and thus the
// application would redirect the user to the login page after a successful login
if (!(SecurityContextHolder.getContext()
.getAuthentication() instanceof AnonymousAuthenticationToken)) {
log.debug("Already logged in, forwarding to home page");
throw new RestartResponseException(getApplication().getHomePage());
}
String redirectUrl = getRedirectUrl();
if (redirectUrl == null) {
log.debug("Authentication required");
}
else {
log.debug("Authentication required (original URL: [{}])", redirectUrl);
}
}
HomeController.java 文件源码
项目:workbenchauth
阅读 33
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied() {
final ModelAndView model = new ModelAndView();
// check if user is login
final Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
final UserDetails userDetail = (UserDetails) auth.getPrincipal();
model.addObject("username", userDetail.getUsername());
}
model.setViewName("403");
return model;
}
AppLocaleResolver.java 文件源码
项目:eds-starter6-jpa
阅读 60
收藏 0
点赞 0
评论 0
@Override
public Locale resolveLocale(HttpServletRequest request) {
Authentication authentication = SecurityContextHolder.getContext()
.getAuthentication();
if (authentication == null
|| authentication instanceof AnonymousAuthenticationToken) {
return request.getLocale();
}
else if (authentication.getPrincipal() instanceof JpaUserDetails) {
return ((JpaUserDetails) authentication.getPrincipal()).getLocale();
}
else if (getDefaultLocale() != null) {
return getDefaultLocale();
}
else {
return Locale.ENGLISH;
}
}