Java Code Examples for org.apache.shiro.subject.Subject#login()

The following examples show how to use org.apache.shiro.subject.Subject#login() . 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: SecurityManagerAssociatingFilter.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
private Response authenticate(UriInfo info, String user, String password) {
    
    _LOG.debug("Received a login request for user {}", user);
    
    Subject currentUser = SecurityUtils.getSubject();
    
    ResponseBuilder rb;
    
    if (!currentUser.isAuthenticated()) {
        _LOG.debug("Authenticating user {}", user);
        UsernamePasswordToken token = new UsernamePasswordToken(user, password);
        token.setRememberMe(true);
        currentUser.login(token);
        
        rb = Response.ok()
                .cookie(new NewCookie(SESSION_COOKIE_NAME, currentUser.getSession().getId().toString(), 
                        info.getBaseUri().getPath(), null, -1, null, -1, null, false, true));
    } else {
        _LOG.debug("The login request for user {} was already authenticated as user {}", user, currentUser.getPrincipal());
        rb = Response.status(Status.CONFLICT);
    }
    return rb.build();
}
 
Example 2
Source File: BaseShiroTest.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
@DisplayName("基本认证测试例")
public void testAuthentication() {

    // 构建 SecurityManager
    DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
    defaultSecurityManager.setRealm(simpleAccountRealm);

    // Subject 提交认证请求
    SecurityUtils.setSecurityManager(defaultSecurityManager); // 设置 SecurityManager
    Subject subject = SecurityUtils.getSubject(); // 获取当前 Subject

    // 登录
    UsernamePasswordToken token = new UsernamePasswordToken("root", "root");
    subject.login(token);

    // subject.isAuthenticated() 用于判断用户是否认证成功
    System.out.println("isAuthenticated:" + subject.isAuthenticated());
    Assertions.assertTrue(subject.isAuthenticated());

    // 登出
    subject.logout();

    System.out.println("isAuthenticated:" + subject.isAuthenticated());
    Assertions.assertFalse(subject.isAuthenticated());
}
 
Example 3
Source File: HmacPermsFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: SystemController.java    From hunt-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 登录
 *
 * @param loginName 登录名
 * @param password  密码
 * @param platform  终端类型
 * @return
 */
@ApiOperation(value = "登录", httpMethod = "POST", produces = "application/json", response = Result.class)
@ResponseBody
@RequestMapping(value = "login", method = RequestMethod.POST)
public Result login(@RequestParam String loginName,
                    @RequestParam String password,
                    @RequestParam int platform,
                    HttpServletRequest request) throws Exception {
    //极限验证二次服务验证
    if (!verifyCaptcha(request)) {
        return Result.instance(ResponseCode.verify_captcha_error.getCode(), ResponseCode.verify_captcha_error.getMsg());
    }
    SysUser user = sysUserService.selectByLoginName(loginName);
    if (user == null) {
        return Result.instance(ResponseCode.unknown_account.getCode(), ResponseCode.unknown_account.getMsg());
    }
    if (user.getStatus() == 3) {
        return Result.instance(ResponseCode.forbidden_account.getCode(), ResponseCode.forbidden_account.getMsg());
    }
    Subject subject = SecurityUtils.getSubject();
    subject.login(new UsernamePasswordToken(loginName, password));
    LoginInfo loginInfo = sysUserService.login(user, subject.getSession().getId(), platform);
    subject.getSession().setAttribute("loginInfo", loginInfo);
    log.debug("登录成功");
    return Result.success(loginInfo);
}
 
Example 5
Source File: Login.java    From Student-Homework-Management-System with MIT License 6 votes vote down vote up
/**
 * QQ登陆解析
 *
 * @param request {@link HttpServletRequest}
 * @return JSP页面
 * @throws LoginException LoginException
 */
@RequestMapping("qqLoginAfter")
public String qqLoginAfter(HttpServletRequest request) throws LoginException {
    String userOpenID = QQLoginUtil.getUserOpenID(request);
    if (userOpenID == null) {
        throw new LoginException("userOpenID==null");
    }
    User userByopenID = userService.getUserEntityByOpenID(userOpenID);
    if (userByopenID == null) {
        request.getSession().setAttribute("userOpenID", userOpenID);
        return "jsp/BindQQ.jsp";
    } else {
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userByopenID.getUsername(), userByopenID.getPassword(), false, request.getRemoteAddr());
        currentUser.login(token);
    }
    return "index.jsp";
}
 
Example 6
Source File: LoginController.java    From Online_Study_System with Apache License 2.0 6 votes vote down vote up
/**
 * 登录表单处理
 * @param userlogin Userlogin对象
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/login", method = {RequestMethod.POST})
public String login(Userlogin userlogin) throws Exception {

    //Shiro实现登录
    UsernamePasswordToken token = new UsernamePasswordToken(userlogin.getName(),
            userlogin.getPassword());
    Subject subject = SecurityUtils.getSubject();

    //如果获取不到用户名就是登录失败,但登录失败的话,会直接抛出异常
    subject.login(token);

    //所有用户均重定向对应的展示课程页面
    if (subject.hasRole(GlobalConstant.ROle_Type.ADMIN.getName())) {
        return "redirect:/admin/showCourse";
    } else if (subject.hasRole(GlobalConstant.ROle_Type.TEACHER.getName())) {
        return "redirect:/teacher/showCourse";
    } else if (subject.hasRole(GlobalConstant.ROle_Type.STUDENT.getName())) {
        return "redirect:/student/showCourse";
    }

    return "../../login";
}
 
Example 7
Source File: JwtShiroInvokeListener.java    From jboot-admin with Apache License 2.0 6 votes vote down vote up
@Override
public void onInvokeBefore(FixedInvocation inv) {
    JbootController controller = (JbootController) inv.getController();
    String jwtToken = controller.getHeader(JwtManager.me().getHttpHeaderName());

    if (StrUtils.isBlank(jwtToken)) {
        inv.invoke();
        return;
    }

    Map jwtParas = JwtManager.me().getParas();
    String userId = String.valueOf(jwtParas.get("userId"));

    AuthenticationToken token = new JwtAuthenticationToken(userId, jwtToken);

    try {
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
    } catch (Exception e) {
        log.error(e.getMessage());
    }
}
 
Example 8
Source File: HmacAuthcFilter.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	if(isHmacSubmission(request)){
		AuthenticationToken token = createHmacToken(request, response);
		try {
			Subject subject = getSubject(request, response);
			subject.login(token);
			return true;
		} 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 9
Source File: DefaultSecuritySystemTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testLogout() throws Exception {
  SecuritySystem securitySystem = this.getSecuritySystem();

  // bind to a servlet request/response
  // this.setupLoginContext( "test" );

  // login
  UsernamePasswordToken token = new UsernamePasswordToken("jcoder", "jcoder");
  Subject subject = securitySystem.getSubject();
  Assert.assertNotNull(subject);
  subject.login(token);

  // check the logged in user
  Subject loggedinSubject = securitySystem.getSubject();
  // Assert.assertEquals( subject.getSession().getId(), loggedinSubject.getSession().getId() );
  Assert.assertTrue(subject.isAuthenticated());
  Assert.assertTrue("Subject principal: " + loggedinSubject.getPrincipal() + " is not logged in",
      loggedinSubject.isAuthenticated());
  loggedinSubject.logout();

  // the current user should be null
  subject = securitySystem.getSubject();
  Assert.assertFalse(subject.isAuthenticated());
  Assert.assertFalse(loggedinSubject.isAuthenticated());
}
 
Example 10
Source File: LoginRestApi.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private JsonResponse<Map<String, String>> proceedToLogin(Subject currentUser, AuthenticationToken token) {
  JsonResponse<Map<String, String>> response = null;
  try {
    logoutCurrentUser();
    currentUser.getSession(true);
    currentUser.login(token);

    Set<String> roles = authenticationService.getAssociatedRoles();
    String principal = authenticationService.getPrincipal();
    String ticket = "anonymous".equals(principal) ? "anonymous" : TicketContainer.instance.getTicket(principal);

    Map<String, String> data = new HashMap<>();
    data.put("principal", principal);
    data.put("roles", GSON.toJson(roles));
    data.put("ticket", ticket);

    response = new JsonResponse<>(Status.OK, "", data);
    // if no exception, that's it, we're done!

    // set roles for user in NotebookAuthorization module
    authorizationService.setRoles(principal, roles);
  } catch (AuthenticationException uae) {
    // username wasn't in the system, show them an error message?
    // password didn't match, try again?
    // account for that username is locked - can't login.  Show them a message?
    // unexpected condition - error?
    LOG.error("Exception in login: ", uae);
  }
  return response;
}
 
Example 11
Source File: UserRealmIT.java    From es with Apache License 2.0 5 votes vote down vote up
@Test(expected = AuthenticationException.class)
public void testLoginFailWithUserPasswordNotMatch() {
    createUser(username, password);

    UsernamePasswordToken upToken = new UsernamePasswordToken(username, password + "1");
    Subject subject = SecurityUtils.getSubject();
    subject.login(upToken);
}
 
Example 12
Source File: BackgroundProgramUserUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
public static void login() throws Exception {
	if (securityManager==null) {
		throw new Exception("Security manager is null!");
	}
	SecurityUtils.setSecurityManager(securityManager);		
	Subject subject = SecurityUtils.getSubject();
	UsernamePasswordToken token = new UsernamePasswordToken(
			Constants.SYSTEM_BACKGROUND_USER, Constants.SYSTEM_BACKGROUND_PASSWORD);
	subject.login(token);
	subjectThreadLocal.set(subject);
}
 
Example 13
Source File: ShiroDialectTest.java    From thymeleaf-extras-shiro with Apache License 2.0 5 votes vote down vote up
@Test
public void testLacksRole() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    setSubject(subjectUnderTest);

    Context context = new Context();
    String result;

    // Guest user
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("LACKSROLE1"));
    assertTrue(result.contains("LACKSROLE2"));

    // Logged in user 1
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertTrue(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("LACKSROLE1"));
    assertFalse(result.contains("LACKSROLE2"));
    subjectUnderTest.logout();

    // Logged in user 2
    subjectUnderTest.login(new UsernamePasswordToken(USER2, PASS2));
    assertFalse(subjectUnderTest.hasRole("rolea")); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("LACKSROLE1"));
    assertTrue(result.contains("LACKSROLE2"));
    subjectUnderTest.logout();
}
 
Example 14
Source File: UserController.java    From songjhh_blog with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(UserCustom userCustom, Model model) {
    Subject subject = SecurityUtils.getSubject();
    if(!subject.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(userCustom.getUsername(), userCustom.getPassword());
        token.setRememberMe(true);
        try {
            subject.login(token);
            Session session = subject.getSession();
            userService.updateLoginLastTime(userService.getByUserName(userCustom.getUsername()),session);
            return "redirect:/";
        } catch (UnknownAccountException uae) {
            model.addAttribute("errorMsg", "username wasn't in the system.");
        } catch (IncorrectCredentialsException ice){
            model.addAttribute("errorMsg", "password didn't match.");
        } catch (LockedAccountException lae) {
            model.addAttribute("errorMsg", "account for that username is locked - can't login.");
        } catch (ExcessiveAttemptsException  eae) {
            model.addAttribute("errorMsg", "password lost miss too much,please try again later.");
        } catch (AuthenticationException ae) {
            model.addAttribute("errorMsg", "unexpected condition.");
        }
        model.addAttribute("userCustom", userCustom);
        return "user/login";
    }
    return "redirect:/";
}
 
Example 15
Source File: LoginController.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
@PostMapping("/login")
public String login(User user) {

    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
            user.getName(), user.getPassword());
    //进行验证,这里可以捕获异常,然后返回对应信息
    subject.login(usernamePasswordToken);

    return "redirect:/home";
}
 
Example 16
Source File: UserController.java    From SENS with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 登录该账号
 *
 * @return 模板路径admin/admin_edit
 */
@GetMapping("/login")
@SystemLog(description = "管理员登录其他用户", type = LogTypeEnum.OPERATION)
public String loginIt(@RequestParam("id") Long userId) {
    User user = userService.get(userId);
    Subject subject = SecurityUtils.getSubject();
    // freeRealm 无需验证账号密码
    UserToken userToken = new UserToken(user.getUserName(), null, LoginTypeEnum.FREE.getValue());
    subject.login(userToken);

    Set<String> permissionUrls = permissionService.findPermissionUrlsByUserId(user.getId());
    subject.getSession().setAttribute("permissionUrls", permissionUrls);
    return "redirect:/admin";
}
 
Example 17
Source File: DefaultSecuritySystemTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testChangePassword_AfterUserLogin() throws UserNotFoundException, NoSuchUserManagerException {
  expectedException.expect(AuthorizationException.class);
  expectedException.expectMessage("jcoder is not permitted to change the password for fakeuser");

  SecuritySystem securitySystem = this.getSecuritySystem();
  Subject subject = securitySystem.getSubject();
  subject.login(new UsernamePasswordToken("jcoder", "jcoder"));

  // change my own
  securitySystem.changePassword("jcoder", "newpassword");

  // change another user's password
  securitySystem.changePassword("fakeuser", "newpassword");
}
 
Example 18
Source File: OauthController.java    From java-platform with Apache License 2.0 4 votes vote down vote up
private void login(OauthUser oauthUser, HttpServletRequest request) {
	OauthUserToken token = new OauthUserToken(oauthUser, request.getRemoteHost(), true);
	Subject subject = SecurityUtils.getSubject();
	subject.login(token);
}
 
Example 19
Source File: RestController.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
/**
	 * 前后端分离的情况之下rest风格登录获取TGT ST
	 * @Description:TODO
	 * @author:hsj qq:2356899074
	 * @time:2017年12月1日 下午2:49:40
	 * @param req
	 * @param respon
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/restlogin")
	public String restlogin(HttpServletRequest req,HttpServletResponse respon)throws Exception{
//		return RestFulLogin.validateFromCAS("hsjhsj", "hsjhsj");
		        //校验有没有username和password
                String username = "hsjhsj";
		        UsernamePasswordToken token = new UsernamePasswordToken("hsjhsj","hsjhsj");
		        //获取当前的Subject  
		        Subject currentUser = SecurityUtils.getSubject();  
		        try {  
		            //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查  
		            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应  
		            //所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法  
		            logger.info("对用户[" + username + "]进行登录验证..验证开始");  
		            currentUser.login(token);  
		            logger.info("对用户[" + username + "]进行登录验证..验证通过");  
		        }catch(UnknownAccountException uae){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");  
		            return "403";
		        }catch(IncorrectCredentialsException ice){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");  
		            return "403";
		        }catch(LockedAccountException lae){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");  
		            return "403";
		        }catch(ExcessiveAttemptsException eae){  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多"); 
		            return "403";
		        }catch(AuthenticationException ae){  
		            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景  
		            logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");  
		            ae.printStackTrace();  
		            return "403";
		        }  
		        //验证是否登录成功  
		        if(currentUser.isAuthenticated()){  
		            logger.info("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");  
		            return "inde";
		        }else{  
		            token.clear();  
		            return "403";
		        }  
	}
 
Example 20
Source File: ShiroController.java    From jboot with Apache License 2.0 3 votes vote down vote up
public void doLogin(){

        Subject subject = SecurityUtils.getSubject();
        subject.login(new TestAuthenticationToken());

//        subject.isAuthenticated();
//        subject.isPermitted()

        renderText("logined success");

    }