@ModelAttribute("login") private MsgTO login(@RequestBody MsgTO msgTo) { Long userId = msgTo.getUserId(); String password = msgTo.getPassword(); SysUserEntity user = ((SysUserService) SpringContextUtils.getBean("sysUserService")).queryObject(userId); if(user==null){ throw new RRException("用户id不存在"); } try { Subject subject = ShiroUtils.getSubject(); // sha256加密 password = new Sha256Hash(password).toHex(); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), password); subject.login(token); } catch (Exception e) { throw new RRException("登录失败"); } msgTo.setUser(user); return msgTo; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { //UsernamePasswordToken对象用来存放提交的登录信息 UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken; log.info("验证当前Subject时获取到token为:" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); // return new SimpleAuthenticationInfo("hsjhsj","8e24137dee97c9bbddb9a0cd6e043be4" , getName()); return new SimpleAuthenticationInfo("hsjhsj","" , getName()); //查出是否有此用户 // TbUser user=null; // if(user!=null){ // 若存在,将此用户存放到登录认证info中,无需自己做密码对比,Shiro会为我们进行密码对比校验 // return new SimpleAuthenticationInfo(user.getUsername(), , getName()); // } // return null; }
/** * 用户登录 * @param request * @param user * @param model * @return */ @RequestMapping(value = "/login",method = RequestMethod.POST) public String login(HttpServletRequest request, AdminUser user, Model model) { if (StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPassword())){ request.setAttribute("msg","用户名或者密码不能为空!"); return "login"; } Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword()); try { subject.login(token); return "redirect:/initPage"; }catch (LockedAccountException lae) { token.clear(); request.setAttribute("msg", "用户已经被锁定不能登录,请与管理员联系!"); return "login"; } catch (AuthenticationException e) { token.clear(); request.setAttribute("msg", "用户或密码不正确!"); return "login"; } }
@RequestMapping(value = "/login", method = { RequestMethod.POST}) public String dashboard(ModelMap map, Admin admin) { String error = null; UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword()); token.setRememberMe(false); try { SecurityUtils.getSubject().login(token); return "redirect:/video/all"; } catch (UnknownAccountException uae) { error = "用户名错误!"; } catch (IncorrectCredentialsException ice) { error = "密码错误!"; } catch (LockedAccountException lae) { error = "用户被锁定!"; } map.addAttribute("error", error); return "login.ftl"; }
@RequestMapping(value = "/tlogin", method = RequestMethod.POST) public String login(String username, String password, HttpServletRequest request) { //String validateCode = (String) ServletActionContext.getRequest().getSession().getAttribute("key"); // if (StringUtils.isNotBlank(checkcode) && checkcode.equals(validateCode)) { // 使用shiri方式 // 获得当前对象的状态:未认证 Subject subject = SecurityUtils.getSubject(); // 用户名密码令牌对象 AuthenticationToken token = new UsernamePasswordToken(username, password); try { subject.login(token); } catch (Exception e) { e.printStackTrace(); return "login"; } User user = (User) subject.getPrincipal(); // user放入session request.getSession().setAttribute("loginUser", user); return "index"; }
@RequestMapping(value = "login", method = RequestMethod.POST) public String login(@ModelAttribute("formDto") LoginDto formDto, BindingResult errors) { UsernamePasswordToken token = formDto.token(); token.setRememberMe(false); try { SecurityUtils.getSubject().login(token); } catch (Exception e) { LOG.debug("Error authenticating.", e); errors.rejectValue("username", null, "The username or password was not correct."); return "login"; } return "redirect:index"; }
protected boolean submitLogin() throws ServletException, IOException { if (isSubmitLogin()) { //login flow try { UsernamePasswordToken token = createUsernamePasswordToken(); SecurityUtils.getSubject().login(token); LOG.debug("Submit login successful"); this.userFirstLogged = true; return false; } catch (Exception ex) { //login failed LOG.debug("Login failed, back to login page too", ex); final HttpServletRequest request = oauthRequest.request(); request.setAttribute("oauth_login_error", true); request.getRequestDispatcher(OAUTH_LOGIN_VIEW) .forward(request, response); return true; } } return false; }
/** * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for the * specified username. */ @Override protected AuthenticationInfo queryForAuthenticationInfo( AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException { final UsernamePasswordToken upToken = ensureUsernamePasswordToken(token); final String userDn = findUserDn(ldapContextFactory, upToken.getUsername()); LdapContext ctx = null; try { // Binds using the username and password provided by the user. ctx = ldapContextFactory.getLdapContext(userDn, upToken.getPassword()); } finally { LdapUtils.closeContext(ctx); } return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword()); }
@Test public void testHelloWorld() { //1、获取 SecurityManager 工厂,此处使用 Ini 配置文件初始化 SecurityManager Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //2、得到 SecurityManager 实例 并绑定给 SecurityUtils SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); //3、得到 Subject 及创建用户名/密码身份验证 Token(即用户身份/凭证) Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("test", "234"); try { //4、登录,即身份验证 subject.login(token); } catch (AuthenticationException e) { //5、身份验证失败 } Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录 //6、退出 subject.logout(); }
private boolean login(Subject subject, HttpServletRequest request) { if("get".equalsIgnoreCase(request.getMethod())) { return false; } String username = request.getParameter("username"); String password = request.getParameter("password"); if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { return false; } UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { subject.login(token); return true; } catch (Exception e) { request.setAttribute("error", "登录失败:" + e.getClass().getName()); return false; } }
public boolean tryLogin(String email, String password, Boolean rememberMe) { org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(email, password); token.setRememberMe(rememberMe); try { currentUser.login(token); System.out.println("User [" + currentUser.getPrincipal().toString() + "] logged in successfully."); // save username in the session currentUser.getSession().setAttribute("username", email); return true; } catch (UnknownAccountException uae) { System.out.println("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { System.out.println("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { System.out.println("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } return false; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // identify account to log to UsernamePasswordToken userPassToken = (UsernamePasswordToken) token; final String username = userPassToken.getUsername(); if (username == null) { return null; } // read password hash and salt from db final User user = UserDAO.getUser(username); if (user == null) { return null; } // return salted credentials SaltedAuthenticationInfo info = new SaltedAuthInfo(username, user.getPassword(), user.getSalt()); return info; }
@PostMapping(value = SUBPATH_LOGIN) public ResponseEntity<UserDto> login(@RequestBody UserDto userDto, UriComponentsBuilder uriComponentsBuilder){ HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,SUBPATH_LOGIN); logger.info("================userInfo================username: " + userDto.getUsername() + ",pw: " + userDto.getPassword()); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(userDto.getUsername(),userDto.getPassword()); //User user = new User("root","root","root","root"); //userDao.save(user); try{ subject.login(token); } catch (AuthenticationException e){ logger.error("======登录失败======"); throw new ResultException(ErrorCode.USERNAMEORPASSWORD.getDesc(),ErrorCode.USERNAMEORPASSWORD); } UserDto loginUserDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("user"); return new ResponseEntity<>(loginUserDto,headers, HttpStatus.OK); }
@RequestMapping(value="/login",method=RequestMethod.POST) public ModelAndView login(User user, String captcha, HttpSession session,HttpServletRequest request) throws Exception{ ModelAndView mv = new ModelAndView(); String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); System.out.println(kaptchaExpected); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword()); try{ subject.login(token); mv.setViewName("redirect:/index.jsp"); } catch (AuthenticationException e){ mv.addObject("message", "login errors"); mv.setViewName("redirect:/backend/login"); } return mv; }
@RequestMapping(value ="/hello") @ResponseBody public String hello(){ Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("zhansan", "123456"); //--4. 登录,即身份验证 try { subject.login(token); } catch (AuthenticationException e) { e.printStackTrace(); } //System.out.println(subject.isAuthenticated()); //System.out.println(subject.getPrincipal()); //-- 6. 退出 System.out.println(subject.isAuthenticated()); subject.logout(); return "hello"; }
/** * 登录 * @param user * @param session * @param request * @return * @throws Exception */ @SystemControllerLog(description="登录系统") @RequestMapping(value="/login",method=RequestMethod.POST) public ModelAndView login(User user, HttpSession session,HttpServletRequest request) throws Exception{ ModelAndView mv = new ModelAndView(); Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getUserPass()); try{ currentUser.login(token); mv.setViewName("redirect:/index.jsp"); } catch (AuthenticationException e){ mv.addObject("message", "login errors"); mv.setViewName("redirect:/backend/login"); } return mv; }
public boolean isValid(String value, ConstraintValidatorContext constraintContext) { if (value != null) { UserPage page = (UserPage) WicketUtils.getPage(); AuthenticationToken token = new UsernamePasswordToken(page.getUser().getName(), value); try { if (SecurityUtils.getSecurityManager().authenticate(token) != null) return true; } catch (Exception e) { } constraintContext.disableDefaultConstraintViolation(); constraintContext.buildConstraintViolationWithTemplate("Current password does not match").addConstraintViolation(); return false; } else { return true; } }
@Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { HttpServletRequest httpRequest = WebUtils.toHttp(request); String authzHeader = httpRequest.getHeader(AUTHORIZATION_HEADER); if (authzHeader != null) { if (authzHeader.toLowerCase(Locale.ENGLISH).startsWith("basic") || authzHeader.toLowerCase(Locale.ENGLISH).startsWith("token")) { String authToken = StringUtils.substringAfter(authzHeader, " "); String decoded = Base64.decodeToString(authToken); String userName = StringUtils.substringBefore(decoded, ":").trim(); String password = StringUtils.substringAfter(decoded, ":").trim(); if (userName.length() != 0 && password.length() != 0) { UsernamePasswordToken token = new UsernamePasswordToken(userName, password); subject.login(token); } } } } return true; }
@PostMapping("/login") public String login(HttpServletRequest request, User user, Model model){ if (StringUtils.isEmpty(user.getLoginId()) || StringUtils.isEmpty(user.getPassword())) { request.setAttribute("msg", "用户名或密码不能为空!"); return "login"; } Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token=new UsernamePasswordToken(user.getLoginId(),user.getPassword()); try { subject.login(token); return "manage"; }catch (LockedAccountException lae) { token.clear(); request.setAttribute("msg", "用户已经被锁定不能登录,请与管理员联系!"); return "login"; } catch (AuthenticationException e) { token.clear(); request.setAttribute("msg", "用户或密码不正确!"); return "login"; } }
/** * testIniRealm * @Description: iniRealm的测试 * @return: void * @Author: BeautifulSoup * @Date: 2017年12月16日 上午11:41:43 */ @Test @Ignore public void testIniRealm(){ Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:inirealm-shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token=new UsernamePasswordToken("james_shu", "1997admin"); try{ subject.login(token); }catch(AuthenticationException e){ e.printStackTrace(); } System.out.println("用户认证状态:"+subject.isAuthenticated()); subject.logout(); System.out.println("用户当前认证状态:"+subject.isAuthenticated()); }
/** * testCustomRealm * @Description: CustomRealm的测试 * @return: void * @Author: BeautifulSoup * @Date: 2017年12月16日 上午11:41:53 */ @Test public void testCustomRealm(){ Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:customrealm-shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token=new UsernamePasswordToken("BeautifulSoup", "1997admin"); try{ subject.login(token); }catch(AuthenticationException e){ e.printStackTrace(); } System.out.println("用户认证状态:"+subject.isAuthenticated()); subject.logout(); System.out.println("用户当前认证状态:"+subject.isAuthenticated()); }
/** * testIniAuthorization * @Description: 使用inirealm完成授权 * @return: void * @Author: BeautifulSoup * @Date: 2017年12月16日 下午3:05:34 */ @Test @Ignore public void testIniAuthorization(){ Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:permission-shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); //首先认证,认证通过之后才能授权 UsernamePasswordToken token=new UsernamePasswordToken("beautifulsoup", "password"); try{ subject.login(token); }catch(AuthenticationException e){ e.printStackTrace(); } System.out.println("用户的认证状态:"+subject.isAuthenticated()); boolean isPermitted=subject.isPermittedAll("user:create:01","user:query"); subject.checkPermissions("user:create:01","user:query"); System.out.println(isPermitted); }
/** * testCustomRealmAuthorization * @Description: 使用自定义realm完成授权 * @return: void * @Author: BeautifulSoup * @Date: 2017年12月16日 下午3:05:46 */ @Test public void testCustomRealmAuthorization(){ Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:customrealm-shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); //首先认证,认证通过之后才能授权 UsernamePasswordToken token=new UsernamePasswordToken("BeautifulSoup", "1997admin"); try{ subject.login(token); }catch(AuthenticationException e){ e.printStackTrace(); } System.out.println("用户的认证状态:"+subject.isAuthenticated()); boolean isPermitted=subject.isPermittedAll("item:query"); System.out.println(isPermitted); }
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; Map<String, Object> params = new HashMap<String, Object>(); params.put("enable", 1); params.put("account", token.getUsername()); Parameter parameter = new Parameter("sysUserService", "queryList").setMap(params); logger.info("{} execute sysUserService.queryList start...", parameter.getNo()); List<?> list = provider.execute(parameter).getList(); logger.info("{} execute sysUserService.queryList end.", parameter.getNo()); if (list.size() == 1) { SysUser user = (SysUser) list.get(0); StringBuilder sb = new StringBuilder(100); for (int i = 0; i < token.getPassword().length; i++) { sb.append(token.getPassword()[i]); } if (user.getPassword().equals(sb.toString())) { WebUtil.saveCurrentUser(user.getId()); saveSession(user.getAccount(), token.getHost()); AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), user.getUserName()); return authcInfo; } logger.warn("USER [{}] PASSWORD IS WRONG: {}", token.getUsername(), sb.toString()); return null; } else { logger.warn("No user: {}", token.getUsername()); return null; } }
/** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; // User user = accountManager.findUserByLoginName(token.getUsername()); //根据loginToken 看能不查到当前token token有效期就1分钟 String tokenPassword=new String(token.getPassword()); User user = accountManager.findUserByLoginNameOrEmail(token.getUsername()); //user.getStandardLock()==1 if (user != null && user.getStatus().intValue()!=0 && !user.getLoginName().endsWith("@chacuo.net")) { return new SimpleAuthenticationInfo(user.getLoginName(), user.getShaPassword() , getName()); } else { return null; } }
@RequestMapping(value = "/signin", method = { RequestMethod.POST}) public String signin(ModelMap map, User user, HttpServletRequest request) { String error; UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPasswd()); token.setRememberMe(null != request.getParameter("rememberme") ? true : false); try { Subject subject = SecurityUtils.getSubject(); subject.login(token); subject.getSession().setAttribute("curUser", userService.findByUsername((String) subject.getPrincipal())); return "redirect:/dashboard/console"; } catch (UnknownAccountException uae) { error = "用户名错误!"; } catch (IncorrectCredentialsException ice) { error = "密码错误!"; } catch (LockedAccountException lae) { error = "用户被锁定!"; } map.addAttribute("error", error); return "signin"; }
@RequestMapping(value = "/signup", method = { RequestMethod.POST}) public String signup(User user, ModelMap map) { //检查用户名是否被注册 User temp = userService.findByUsername(user.getUsername()); if (null == temp) { //注册 String passwdTemp = user.getPasswd(); passwordHelper.encryptPassword(user); userService.insert(user); //登录到shiro中 UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), passwdTemp); token.setRememberMe(true); Subject subject = SecurityUtils.getSubject(); subject.login(token); subject.getSession().setAttribute("curUser", user); return "redirect:/dashboard/console"; } else { map.addAttribute("error", "用户名已经被占用!"); return "signup"; } }
@RequestMapping(value = "/changepwd", method = { RequestMethod.POST}) public String changepwd(ModelMap map, User user, @RequestParam(value = "passwdnew", required = true) String passwdnew) { //验证当前账号 UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPasswd()); token.setRememberMe(false); try { SecurityUtils.getSubject().login(token); //验证通过更新用户密码 user.setId(getCurrentUser().getId()); user.setPasswd(passwdnew); passwordHelper.encryptPassword(user); userService.updateById(user); return "redirect:/dashboard/console"; } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) { map.addAttribute("exception", e.getMessage()); return "common/error"; } }
@RequestMapping(value="/login",method=RequestMethod.POST) public ModelAndView login(User user, String captcha, HttpSession session,HttpServletRequest request) throws Exception{ ModelAndView mv = new ModelAndView(); String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); //--System.out.println(kaptchaExpected); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword()); try{ subject.login(token); System.out.println(subject.getSession().getId()); System.out.println(session.getId()); mv.setViewName("redirect:/hello"); } catch (AuthenticationException e){ mv.addObject("message", "login errors"); mv.setViewName("redirect:/backend/login"); } return mv; }
public static void main(String[] args) { //此处从ini文件来实现用用户角色权限配置,实际多从数据库表来实现 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini.bak"); //SercurityManager 对象 SecurityManager instance = factory.getInstance(); SecurityUtils.setSecurityManager(instance); //测试用户 Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin"); boolean result = false; try { currentUser.login(token); result = true; LOG.debug("认证成功"); } catch (Exception e) { result = false; LOG.debug("认证失败"); } }
@Log @OnEvent(value = EventConstants.VALIDATE, component = "loginForm") public void validation() { if (!loginForm.isValid()) { return; } //LOG.debug("onValidateLoginForm [" + username + "] "); try { Subject subject = SecurityUtils.getSubject(); if (!subject.isAuthenticated()) { // http://shiro.apache.org/static/1.2.2/apidocs/org/apache/shiro/authc/UsernamePasswordToken.html UsernamePasswordToken token = new UsernamePasswordToken(username, password); //token.setRememberMe(rememberMe); subject.login(token); token.clear(); LOG.debug("User [" + subject.getPrincipal() + "] logged in successfully."); } else { LOG.debug("User [" + subject.getPrincipal() + "] failed to log."); } } catch (Exception e) { loginForm.recordError("Error " + e.getMessage()); } }
@Test public void testHelloworld(){ //1.获取SecurityManagerFactory,此处用shiro.ini来初始化 Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); //2.得到securityManager实例 SecurityManager securityManager = factory.getInstance(); //3.绑定给securityManager SecurityUtils.setSecurityManager(securityManager); //4.获取subject Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123"); try { //5.登录 subject.login(token); } catch (Exception e) { //6.身份验证失败 } Assert.assertEquals(true, subject.isAuthenticated()); //7.登出 subject.logout(); }
@Test public void testCustomRealm(){ //1.获取SecurityManagerFactory,此处用shiro-realm.ini来初始化(使用自定义realm) Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini"); //2.得到securityManager实例 SecurityManager securityManager = factory.getInstance(); //3.绑定给securityManager SecurityUtils.setSecurityManager(securityManager); //4.获取subject Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123"); try { //5.登录 subject.login(token); } catch (Exception e) { //6.身份验证失败 } Assert.assertEquals(true, subject.isAuthenticated()); //7.登出 subject.logout(); }
@Test public void testCustomMultiRealm(){ //1.获取SecurityManagerFactory,此处用shiro.ini来初始化(使用自定义realm) Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-multi-realm.ini"); //2.得到securityManager实例 SecurityManager securityManager = factory.getInstance(); //3.绑定给securityManager SecurityUtils.setSecurityManager(securityManager); //4.获取subject Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("wang", "123"); try { //5.登录 subject.login(token); } catch (Exception e) { //6.身份验证失败 } Assert.assertEquals(true, subject.isAuthenticated()); //7.登出 subject.logout(); }
@Test public void testJDBCRealm(){ //1.获取SecurityManagerFactory,此处用shiro-jdbc-realm.ini来初始化(使用自定义realm) Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-jdbc-realm.ini"); //2.得到securityManager实例 SecurityManager securityManager = factory.getInstance(); //3.绑定给securityManager SecurityUtils.setSecurityManager(securityManager); //4.获取subject Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123"); try { //5.登录 subject.login(token); } catch (Exception e) { //6.身份验证失败 } Assert.assertEquals(true, subject.isAuthenticated()); //7.登出 subject.logout(); }
@Test public void testGuest() { Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject(); setSubject(subjectUnderTest); Context context = new Context(); String result; // Guest user result = templateEngine.process(TEST_TEMPL, context); assertFalse(result.contains("shiro:")); assertTrue(result.contains("GUEST1")); assertTrue(result.contains("GUEST2")); // Logged in user subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1)); result = templateEngine.process(TEST_TEMPL, context); assertFalse(result.contains("shiro:")); assertFalse(result.contains("GUEST1")); assertFalse(result.contains("GUEST2")); subjectUnderTest.logout(); }
@Test public void testUser() { Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject(); setSubject(subjectUnderTest); Context context = new Context(); String result; // Guest user result = templateEngine.process(TEST_TEMPL, context); assertFalse(result.contains("shiro:")); assertFalse(result.contains("USER1")); assertFalse(result.contains("USER2")); // Logged in user subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1)); result = templateEngine.process(TEST_TEMPL, context); assertFalse(result.contains("shiro:")); assertTrue(result.contains("USER1")); assertTrue(result.contains("USER2")); subjectUnderTest.logout(); }