Java Code Examples for org.apache.shiro.subject.Subject#isAuthenticated()
The following examples show how to use
org.apache.shiro.subject.Subject#isAuthenticated() .
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 File: HmacPermsFilter.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 6 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = getSubject(request, response); if ((null == subject || !subject.isAuthenticated()) && isHmacSubmission(request)) { AuthenticationToken token = createHmacToken(request, response); try { subject = getSubject(request, response); subject.login(token); return this.checkPerms(subject,mappedValue); } catch (AuthenticationException e) { LOGGER.error(request.getRemoteHost()+" HMAC鉴权 "+e.getMessage()); CommonUtils.restFailed(WebUtils.toHttp(response) ,ShiroProperties.REST_CODE_AUTH_UNAUTHORIZED,e.getMessage()); } } return false; }
Example 2
Source File: RegisterController.java From PhrackCTF-Platform-Personal with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/register",method = RequestMethod.GET) public ModelAndView doGetRegister() throws Exception { ModelAndView mv = new ModelAndView("register"); Subject currentUser = SecurityUtils.getSubject(); CommonUtils.setUserInfo(currentUser, userServices, submissionServices,mv); CommonUtils.setControllerName(request, mv); if (currentUser.isAuthenticated()||currentUser.isRemembered()) { return new ModelAndView("redirect:/home"); } List<Countries> cts = countryServices.SelectAllCountry(); mv.addObject("country",cts); mv.setViewName("register"); return mv; }
Example 3
Source File: SecurityManagerAssociatingFilter.java From aries-jax-rs-whiteboard with Apache License 2.0 | 5 votes |
private void logout() { _LOG.debug("Received a logout request"); Subject currentUser = SecurityUtils.getSubject(); if (currentUser.isAuthenticated()) { _LOG.debug("Logging out user {}", currentUser.getPrincipal()); currentUser.logout(); } }
Example 4
Source File: LoginController.java From MultimediaDesktop with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/user/logout", method = RequestMethod.GET) public String logout() { Subject subject = SecurityUtils.getSubject(); if (subject != null && subject.isAuthenticated()) { subject.logout(); } return "login"; }
Example 5
Source File: NexusBasicHttpAuthenticationFilter.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
/** * Permissive {@link AuthorizationException} 401 and 403 handling. */ @Override protected void cleanup(final ServletRequest request, final ServletResponse response, Exception failure) throws ServletException, IOException { // decode target exception Throwable cause = failure; if (cause instanceof ServletException) { cause = cause.getCause(); } // special handling for authz failures due to permissive if (cause instanceof AuthorizationException) { // clear the failure failure = null; Subject subject = getSubject(request, response); boolean authenticated = subject.getPrincipal() != null && subject.isAuthenticated(); if (authenticated) { // authenticated subject -> 403 forbidden WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN); } else { // unauthenticated subject -> 401 inform to authenticate try { // TODO: Should we build in browser detecting to avoid sending 401, should that be its own filter? onAccessDenied(request, response); } catch (Exception e) { failure = e; } } } super.cleanup(request, response, failure); }
Example 6
Source File: ShiroJwtVerifyingFilter.java From cassandra-reaper with Apache License 2.0 | 5 votes |
static Subject getJwtSubject(Subject nonJwt, ServletRequest req, ServletResponse res) { return null != nonJwt.getPrincipal() && (nonJwt.isRemembered() || nonJwt.isAuthenticated()) ? nonJwt : new WebSubject.Builder(req, res) .principals(new SimplePrincipalCollection(getJwtUser(req).get(), "jwtRealm")) .buildSubject(); }
Example 7
Source File: HmacAuthcFilter.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 5 votes |
@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = getSubject(request, response); if (null != subject && subject.isAuthenticated()) { return true; } return false; }
Example 8
Source File: CentralAuthenticationHandler.java From super-cloudops with Apache License 2.0 | 5 votes |
@Override public LoggedModel loggedin(String grantAppname, Subject subject) { hasTextOf(grantAppname, "grantAppname"); // Check authentication. if (nonNull(subject) && subject.isAuthenticated() && !isBlank((String) subject.getPrincipal())) { Session session = subject.getSession(); // Generate granting ticket. Same: CAS/service-ticket String grantTicket = null; // If the ticket has been generated in the previous // moment.(currently?) GrantApp grant = getGrantCredentials(session).getGrantApp(grantAppname); if (!isNull(grant)) { grantTicket = grant.getGrantTicket(); } else { // Init generate grantCredentials grantTicket = generateGrantTicket(); log.info("New init grantTicket: {}, grantAppname: {}", grantTicket, grantAppname); } // Puts grantInfo session => applications putGrantCredentials(session, grantAppname, new GrantApp().setGrantTicket(grantTicket)); return new LoggedModel(grantTicket); } throw new AuthenticationException("Unauthenticated"); }
Example 9
Source File: BaseController.java From SENS with GNU General Public License v3.0 | 5 votes |
/** * 当前登录用户 * * @return */ public User getLoginUser() { Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { return (User) subject.getPrincipal(); } return null; }
Example 10
Source File: UserController.java From MyBlog with Apache License 2.0 | 5 votes |
@PostMapping("isLogin") @ResponseBody public MyResponse isLogin() { Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated() || subject.isRemembered()) { return MyResponse.createResponse(ResponseEnum.ALREADY_LOGIN, SecurityUtils.getSubject().getPrincipal().toString()); } return MyResponse.createResponse(ResponseEnum.SUCC); }
Example 11
Source File: LoginController.java From erp-framework with MIT License | 5 votes |
@GetMapping("/login") public String login(HttpServletRequest request){ logger.info("当前的路径为:" + request.getRequestURI()); Subject s = SecurityUtils.getSubject(); logger.info("是否记住登录--》" + s.isRemembered() + "; 是否有权限登录" + s.isAuthenticated()); if(s.isAuthenticated()){ return "redirect:index"; }else { return "login"; } }
Example 12
Source File: ShiroPermissingTag.java From mumu with Apache License 2.0 | 4 votes |
/** * 验证是否为未认证通过用户,与 isAuthenticated 标签相对应,与 isGuest 标签的区别是,该标签包含已记住用户。 * @return 用户是否未通过认证 */ public boolean isNotAuthenticated() { Subject subject = SecurityUtils.getSubject(); return subject == null || subject.isAuthenticated() == false; }
Example 13
Source File: SubjectAuthResource.java From shiro-jersey with Apache License 2.0 | 4 votes |
@GET public String get(@Auth Subject subject) { if (!subject.isAuthenticated()) throw new UnauthenticatedException(); return Double.toString(Math.random()); }
Example 14
Source File: SecurityInterceptor.java From phone with Apache License 2.0 | 4 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (logger.isDebugEnabled()) { logger.debug("preHandle(HttpServletRequest, HttpServletResponse, Object) - start"); //$NON-NLS-1$ } Subject subject = SecurityUtils.getSubject(); String requestUrl = request.getRequestURI().replace(request.getContextPath(), ""); if (logger.isDebugEnabled()) { logger.debug(StringUtil.appendStringNotNull("###", "请求的url",requestUrl)); //$NON-NLS-1$ } boolean res = ArrayUtil.foreach(igoreRegexUrls, (v,i) -> { return !requestUrl.matches(v);// 如果匹配则不再循环 }); // 如果返回false,则表示匹配忽略的url if (!res) { if (logger.isDebugEnabled()) { logger.debug("preHandle(HttpServletRequest, HttpServletResponse, Object) - end"); //$NON-NLS-1$ } return true; } System.out.println(requestUrl); boolean checkResult = false; // 如果已登录则直接跳转 if (subject != null && subject.isAuthenticated()) { // 判断是否是访问url if (requestUrl.matches(".+\\.(html|jsp)")) { checkResult = processMenuSecurity(requestUrl,request); } else { checkResult = processFuncSecurity(requestUrl); } // 功能 } if (!checkResult) { redirect(response); if (logger.isDebugEnabled()) { logger.debug("preHandle(HttpServletRequest, HttpServletResponse, Object) - end"); //$NON-NLS-1$ } return false; } if (logger.isDebugEnabled()) { logger.debug("preHandle(HttpServletRequest, HttpServletResponse, Object) - end"); //$NON-NLS-1$ } return true; }
Example 15
Source File: ShiroAuthenticationService.java From zeppelin with Apache License 2.0 | 4 votes |
/** * Return the roles associated with the authenticated user if any otherwise returns empty set. * TODO(prasadwagle) Find correct way to get user roles (see SHIRO-492) * * @return shiro roles */ @Override public Set<String> getAssociatedRoles() { Subject subject = org.apache.shiro.SecurityUtils.getSubject(); HashSet<String> roles = new HashSet<>(); Map allRoles = null; if (subject.isAuthenticated()) { Collection<Realm> realmsList = getRealmsList(); for (Realm realm : realmsList) { String name = realm.getClass().getName(); if (name.equals("org.apache.shiro.realm.text.IniRealm")) { allRoles = ((IniRealm) realm).getIni().get("roles"); break; } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) { try { AuthorizationInfo auth = ((LdapRealm) realm) .queryForAuthorizationInfo( new SimplePrincipalCollection(subject.getPrincipal(), realm.getName()), ((LdapRealm) realm).getContextFactory()); if (auth != null) { roles = new HashSet<>(auth.getRoles()); } } catch (NamingException e) { LOGGER.error("Can't fetch roles", e); } break; } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) { allRoles = ((ActiveDirectoryGroupRealm) realm).getListRoles(); break; } } if (allRoles != null) { Iterator it = allRoles.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if (subject.hasRole((String) pair.getKey())) { roles.add((String) pair.getKey()); } } } } return roles; }
Example 16
Source File: KeepOneUserFilter.java From jsets-shiro-spring-boot-starter with Apache License 2.0 | 4 votes |
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { Subject subject = getSubject(request, response); if (!subject.isAuthenticated() && !subject.isRemembered()) { return this.respondLogin(request, response); } String account = (String) subject.getPrincipal(); String loginedSessionId = this.cacheDelegator.getKeepUser(account); Session loginedSession = null; Session currentSession = subject.getSession(); String currentSessionId = (String) currentSession.getId(); if(currentSessionId.equals(loginedSessionId)) { return true; } else if (Strings.isNullOrEmpty(loginedSessionId)){ this.cacheDelegator.putKeepUser(account, currentSessionId); return true; } else if (null==currentSession.getAttribute(ShiroProperties.ATTRIBUTE_SESSION_KICKOUT)) { this.cacheDelegator.putKeepUser(account, currentSessionId); try{ loginedSession = this.sessionManager.getSession(new DefaultSessionKey(loginedSessionId)); if(null != loginedSession){ loginedSession.setAttribute(ShiroProperties.ATTRIBUTE_SESSION_KICKOUT,Boolean.TRUE); } } catch(SessionException e){ LOGGER.warn(e.getMessage()); } } if (null!=currentSession.getAttribute(ShiroProperties.ATTRIBUTE_SESSION_KICKOUT)) { subject.logout(); String loginedHost = ""; Date loginedTime = null; if(null != loginedSession){ loginedHost = loginedSession.getHost(); loginedTime = loginedSession.getStartTimestamp(); } this.authListenerManager.onKeepOneKickout(request, account, loginedHost, loginedTime); return this.respondRedirect(request, response,this.properties.getKickoutUrl()); } return true; }
Example 17
Source File: LoginFormController.java From es with Apache License 2.0 | 4 votes |
@RequestMapping(value = {"/{login:login;?.*}"}) //spring3.2.2 bug see http://jinnianshilongnian.iteye.com/blog/1831408 public String loginForm(HttpServletRequest request, ModelMap model) { //表示退出 if (!StringUtils.isEmpty(request.getParameter("logout"))) { model.addAttribute(Constants.MESSAGE, messageSource.getMessage("user.logout.success", null, null)); } //表示用户删除了 @see org.apache.shiro.web.filter.user.SysUserFilter if (!StringUtils.isEmpty(request.getParameter("notfound"))) { model.addAttribute(Constants.ERROR, messageSource.getMessage("user.notfound", null, null)); } //表示用户被管理员强制退出 if (!StringUtils.isEmpty(request.getParameter("forcelogout"))) { model.addAttribute(Constants.ERROR, messageSource.getMessage("user.forcelogout", null, null)); } //表示用户输入的验证码错误 if (!StringUtils.isEmpty(request.getParameter("jcaptchaError"))) { model.addAttribute(Constants.ERROR, messageSource.getMessage("jcaptcha.validate.error", null, null)); } //表示用户锁定了 @see org.apache.shiro.web.filter.user.SysUserFilter if (!StringUtils.isEmpty(request.getParameter("blocked"))) { User user = (User) request.getAttribute(Constants.CURRENT_USER); String reason = userStatusHistoryService.getLastReason(user); model.addAttribute(Constants.ERROR, messageSource.getMessage("user.blocked", new Object[]{reason}, null)); } if (!StringUtils.isEmpty(request.getParameter("unknown"))) { model.addAttribute(Constants.ERROR, messageSource.getMessage("user.unknown.error", null, null)); } //登录失败了 提取错误消息 Exception shiroLoginFailureEx = (Exception) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (shiroLoginFailureEx != null) { model.addAttribute(Constants.ERROR, shiroLoginFailureEx.getMessage()); } //如果用户直接到登录页面 先退出一下 //原因:isAccessAllowed实现是subject.isAuthenticated()---->即如果用户验证通过 就允许访问 // 这样会导致登录一直死循环 Subject subject = SecurityUtils.getSubject(); if (subject != null && subject.isAuthenticated()) { subject.logout(); } //如果同时存在错误消息 和 普通消息 只保留错误消息 if (model.containsAttribute(Constants.ERROR)) { model.remove(Constants.MESSAGE); } return "front/login"; }
Example 18
Source File: UserSessionBean.java From web-budget with GNU General Public License v3.0 | 4 votes |
/** * @return if the current session of the user is valid or not */ public boolean isValid() { final Subject subject = this.getSubject(); return subject.isAuthenticated() && subject.getPrincipal() != null; }
Example 19
Source File: UserController.java From demo-springmvc-shiro with Apache License 2.0 | 4 votes |
@RequestMapping(value="/login", method=RequestMethod.POST) public String login(String username, String password, HttpServletRequest request){ System.out.println("-------------------------------------------------------"); String rand = (String)request.getSession().getAttribute("rand"); String captcha = WebUtils.getCleanParam(request, "captcha"); System.out.println("用户["+username+"]登录时输入的验证码为["+captcha+"],HttpSession中的验证码为["+rand+"]"); if(!StringUtils.equals(rand, captcha)){ request.setAttribute("message_login", "验证码不正确"); return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/"; } UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); System.out.print("为验证登录用户而封装的Token:"); System.out.println(ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); //获取当前的Subject Subject currentUser = SecurityUtils.getSubject(); try { //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查 //每个Realm都能在必要时对提交的AuthenticationTokens作出反应 //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法 System.out.println("对用户[" + username + "]进行登录验证...验证开始"); currentUser.login(token); System.out.println("对用户[" + username + "]进行登录验证...验证通过"); }catch(UnknownAccountException uae){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,未知账户"); request.setAttribute("message_login", "未知账户"); }catch(IncorrectCredentialsException ice){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误的凭证"); request.setAttribute("message_login", "密码不正确"); }catch(LockedAccountException lae){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,账户已锁定"); request.setAttribute("message_login", "账户已锁定"); }catch(ExcessiveAttemptsException eae){ System.out.println("对用户[" + username + "]进行登录验证...验证未通过,错误次数过多"); request.setAttribute("message_login", "用户名或密码错误次数过多"); }catch(AuthenticationException ae){ //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景 System.out.println("对用户[" + username + "]进行登录验证...验证未通过,堆栈轨迹如下"); ae.printStackTrace(); request.setAttribute("message_login", "用户名或密码不正确"); } //验证是否登录成功 if(currentUser.isAuthenticated()){ System.out.println("用户[" + username + "]登录认证通过(这里可进行一些认证通过后的系统参数初始化操作)"); return "main"; }else{ token.clear(); return InternalResourceViewResolver.FORWARD_URL_PREFIX + "/"; } }
Example 20
Source File: AuthenticationFilter.java From tapestry-security with Apache License 2.0 | 2 votes |
/** * Determines whether the current subject is authenticated. * <p/> * The default implementation {@link #getSubject(javax.servlet.ServletRequest, javax.servlet.ServletResponse) acquires} * the currently executing Subject and then returns * {@link org.apache.shiro.subject.Subject#isAuthenticated() subject.isAuthenticated()}; * * @return true if the subject is authenticated; false if the subject is unauthenticated */ protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { Subject subject = getSubject(request, response); return subject.isAuthenticated(); }