Search in sources :

Example 61 with Session

use of org.apache.shiro.session.Session in project tutorials by eugenp.

the class Main method main.

public static void main(String[] args) {
    Realm realm = new MyCustomRealm();
    SecurityManager securityManager = new DefaultSecurityManager(realm);
    SecurityUtils.setSecurityManager(securityManager);
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
        token.setRememberMe(true);
        try {
            currentUser.login(token);
        } catch (UnknownAccountException uae) {
            log.error("Username Not Found!", uae);
        } catch (IncorrectCredentialsException ice) {
            log.error("Invalid Credentials!", ice);
        } catch (LockedAccountException lae) {
            log.error("Your Account is Locked!", lae);
        } catch (AuthenticationException ae) {
            log.error("Unexpected Error!", ae);
        }
    }
    log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    if (currentUser.hasRole("admin")) {
        log.info("Welcome Admin");
    } else if (currentUser.hasRole("editor")) {
        log.info("Welcome, Editor!");
    } else if (currentUser.hasRole("author")) {
        log.info("Welcome, Author");
    } else {
        log.info("Welcome, Guest");
    }
    if (currentUser.isPermitted("articles:compose")) {
        log.info("You can compose an article");
    } else {
        log.info("You are not permitted to compose an article!");
    }
    if (currentUser.isPermitted("articles:save")) {
        log.info("You can save articles");
    } else {
        log.info("You can not save articles");
    }
    if (currentUser.isPermitted("articles:publish")) {
        log.info("You can publish articles");
    } else {
        log.info("You can not publish articles");
    }
    Session session = currentUser.getSession();
    session.setAttribute("key", "value");
    String value = (String) session.getAttribute("key");
    if (value.equals("value")) {
        log.info("Retrieved the correct value! [" + value + "]");
    }
    currentUser.logout();
    System.exit(0);
}
Also used : SecurityManager(org.apache.shiro.mgt.SecurityManager) DefaultSecurityManager(org.apache.shiro.mgt.DefaultSecurityManager) DefaultSecurityManager(org.apache.shiro.mgt.DefaultSecurityManager) IniRealm(org.apache.shiro.realm.text.IniRealm) Realm(org.apache.shiro.realm.Realm) Subject(org.apache.shiro.subject.Subject) Session(org.apache.shiro.session.Session)

Example 62 with Session

use of org.apache.shiro.session.Session in project Workload by amoxu.

the class UserController method forget.

@RequestMapping(value = "/auth/find", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8", method = { RequestMethod.POST })
@ResponseBody
public // 注册
String forget(HttpServletRequest request) throws Exception {
    // System.out.println(account.getName() + " " + account.getPsw() + " " + account.getMail());
    Subject currentUser = SecurityUtils.getSubject();
    Session session = currentUser.getSession();
    String username = request.getParameter("user");
    String captcha = request.getParameter("captcha");
    if (session.getAttribute("rand") == null || !session.getAttribute("rand").toString().equalsIgnoreCase(captcha)) {
        return "{\"status\":1,\"msg\":\"请重新输入验证码!\"}";
    }
    AjaxResult result = new AjaxResult();
    User user = userService.findByName(username);
    if (null != user) {
        result.ok();
        String md5 = Encryp.encryptionStr(new Random().nextInt(256) + new Date().getTime() + username, Encryp.MD5);
        result.setMsg(md5);
        session.setAttribute("md5", md5);
        session.setAttribute("anser", user.getAnswer());
        List list = new ArrayList();
        list.add(user.getQuestion());
        result.setData(list);
    }
    return JSON.toJSONString(result);
}
Also used : AjaxResult(com.hfut.entity.AjaxResult) User(com.hfut.entity.User) Random(java.util.Random) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Subject(org.apache.shiro.subject.Subject) Date(java.util.Date) Session(org.apache.shiro.session.Session) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 63 with Session

use of org.apache.shiro.session.Session in project Workload by amoxu.

the class UserController method login.

// 登录表单处理
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
@ResponseBody
public String login(User user) throws Exception {
    // Shiro实现登录
    Subject currentUser = SecurityUtils.getSubject();
    Session session = currentUser.getSession();
    if (session.getAttribute("rand") == null || !session.getAttribute("rand").toString().equalsIgnoreCase(user.getMail())) {
        return "{\"status\":1,\"msg\":\"请重新输入验证码!\"}";
    }
    System.out.println(user.getUser() + " " + user.getPassword());
    String psw = ToolKit.psw2pwd(user.getPassword());
    UsernamePasswordToken token = new UsernamePasswordToken(user.getUser(), psw);
    Subject subject = SecurityUtils.getSubject();
    // 如果获取不到用户名就是登录失败,但登录失败的话,会直接抛出异常
    subject.login(token);
    if (subject.hasRole("教师")) {
        return "{\"status\":0,\"msg\":\"/teacher/myzone.html\"}";
    } else if (subject.hasRole("超级管理员")) {
        return "{\"status\":0,\"msg\":\"../index.html\"}";
    }
    return "{\"status\":1,\"msg\":\"/author.html\"}";
}
Also used : Subject(org.apache.shiro.subject.Subject) Session(org.apache.shiro.session.Session) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 64 with Session

use of org.apache.shiro.session.Session in project Workload by amoxu.

the class UserController method reset.

@RequestMapping(value = "/auth/anser", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8", method = { RequestMethod.POST })
@ResponseBody
public // 重置密码
String reset(HttpServletRequest request) throws Exception {
    Subject currentUser = SecurityUtils.getSubject();
    Session session = currentUser.getSession();
    String username = request.getParameter("user");
    String captcha = request.getParameter("captcha");
    String md5 = request.getParameter("md5");
    String question = request.getParameter("question");
    String answer = request.getParameter("answer");
    String password = request.getParameter("password");
    if (session.getAttribute("rand") == null || !session.getAttribute("rand").toString().equalsIgnoreCase(captcha)) {
        return "{\"status\":1,\"msg\":\"请重新输入验证码!\"}";
    }
    boolean ss = !session.getAttribute("md5").toString().equals(md5);
    System.out.println(session.getAttribute("md5").toString());
    System.out.println(request.getParameter("md5"));
    if (session.getAttribute("MD5") != null && ss) {
        return "{\"status\":1,\"msg\":\"请刷新重试!\"}";
    }
    String psw = Encryp.strDec(password, "amoxu", "amoxu", "amoxu");
    System.out.println(psw);
    // 加密MD5 32
    psw = Encryp.encryptionStr(psw + "amoxu", Encryp.MD5);
    AjaxResult result = new AjaxResult();
    try {
        User user = userService.findByName(username);
        if (user.getAnswer() != null && user.getAnswer().equals(answer) && user.getQuestion().equals(question)) {
            user.setPassword(psw);
            userService.updateUser(user);
            currentUser.logout();
            System.out.println(psw);
            result.ok();
            result.setMsg("修改成功,重新登录。");
            return JSON.toJSONString(result);
        } else {
            result.failed();
            result.setMsg("答案错误。");
            return JSON.toJSONString(result);
        }
    } catch (Exception e) {
        throw new CustomException("请检查数据是否正确");
    }
}
Also used : AjaxResult(com.hfut.entity.AjaxResult) User(com.hfut.entity.User) CustomException(com.hfut.exception.CustomException) Subject(org.apache.shiro.subject.Subject) CustomException(com.hfut.exception.CustomException) Session(org.apache.shiro.session.Session) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 65 with Session

use of org.apache.shiro.session.Session in project springBoot-learn-demo by nbfujx.

the class RedisSessionDAO method doReadSession.

// 获取session
@Override
protected Session doReadSession(Serializable sessionId) {
    this.logger.info("获取session:{}", sessionId);
    // 先从缓存中获取session,如果没有再去数据库中获取
    Session session = super.doReadSession(sessionId);
    if (session == null) {
        session = (Session) redisTemplate.opsForValue().get(prefix + sessionId.toString());
    }
    return session;
}
Also used : Session(org.apache.shiro.session.Session)

Aggregations

Session (org.apache.shiro.session.Session)93 Subject (org.apache.shiro.subject.Subject)34 Test (org.junit.Test)21 Serializable (java.io.Serializable)11 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)8 UsernamePasswordToken (org.apache.shiro.authc.UsernamePasswordToken)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 SecurityManager (org.apache.shiro.mgt.SecurityManager)5 SessionListener (org.apache.shiro.session.SessionListener)5 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)5 User (com.hfut.entity.User)4 Subject (ddf.security.Subject)4 ApiOperation (io.swagger.annotations.ApiOperation)4 Date (java.util.Date)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 AuthenticationException (org.apache.shiro.authc.AuthenticationException)4 InvalidSessionException (org.apache.shiro.session.InvalidSessionException)4 SessionListenerAdapter (org.apache.shiro.session.SessionListenerAdapter)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3