org.apache.shiro.authc.UsernamePasswordToken Java Examples

The following examples show how to use org.apache.shiro.authc.UsernamePasswordToken. 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: LoginServiceImpl.java    From SpringBoot-Shiro-Vue-master-20180625 with Apache License 2.0 6 votes vote down vote up
/**
 * 登录表单提交
 *
 * @param jsonObject
 * @return
 */
@Override
public JSONObject authLogin(JSONObject jsonObject) {
    String username = jsonObject.getString("username");
    String password = jsonObject.getString("password");
    JSONObject returnData = new JSONObject();
    Subject currentUser = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    try {
        currentUser.login(token);
        returnData.put("result", "success");
    } catch (AuthenticationException e) {
        returnData.put("result", "fail");
    }
    return CommonUtil.successJson(returnData);
}
 
Example #2
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 #3
Source File: Login.java    From Student-Homework-Management-System with MIT License 6 votes vote down vote up
/**
 * 将QQ绑定到用户
 *
 * @param username 用户名
 * @param password 密码
 * @param model    {@link Model}
 * @param request  {@link HttpServletRequest}
 * @return JSP页面
 */
@RequestMapping("bindQQ")
public String bindQQ(String username, String password, Model model, HttpServletRequest request) {
    String userOpenID = (String) request.getSession().getAttribute("userOpenID");
    String passwd = userService.getPasswd(username);
    if (passwd == null) {
        model.addAttribute("returninfo", "输入的学号不存在,请重试!");
        return "jsp/BindQQ.jsp";
    }
    if (!(passwd.equals(password))) {
        model.addAttribute("returninfo", "密码错误,请重试!");
        return "jsp/BindQQ.jsp";
    }
    Subject currentUser = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(username, password, false, request.getRemoteAddr());
    currentUser.login(token);
    User user = (User) SecurityUtils.getSubject().getPrincipal();
    user.setUserOpenID(userOpenID);
    userService.insertQQIDByUID(user);
    return "index.jsp";
}
 
Example #4
Source File: GitlabAuthenticatingRealm.java    From nexus3-gitlabauth-plugin with MIT License 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (!(token instanceof UsernamePasswordToken)) {
        throw new UnsupportedTokenException(String.format("Token of type %s  is not supported. A %s is required.",
                token.getClass().getName(), UsernamePasswordToken.class.getName()));
    }

    UsernamePasswordToken t = (UsernamePasswordToken) token;
    LOGGER.info("doGetAuthenticationInfo for {}", ((UsernamePasswordToken) token).getUsername());

    GitlabPrincipal authenticatedPrincipal;
    try {
        authenticatedPrincipal = gitlabClient.authz(t.getUsername(), t.getPassword());
        LOGGER.info("Successfully authenticated {}",t.getUsername());
    } catch (GitlabAuthenticationException e) {
        LOGGER.warn("Failed authentication", e);
        return null;
    }

    return createSimpleAuthInfo(authenticatedPrincipal, t);
}
 
Example #5
Source File: SessionResource.java    From airpal with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/login")
public void doLogin(
        @Context HttpServletRequest request,
        @Context HttpServletResponse response,
        @FormParam("username") String username,
        @FormParam("password") String password)
        throws IOException
{
    Subject currentUser = SecurityUtils.getSubject();
    if (!currentUser.isAuthenticated()) {
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        currentUser.login(token);
    }

    WebUtils.redirectToSavedRequest(request, response, "/app");
}
 
Example #6
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 #7
Source File: LoginController.java    From v-mock with MIT License 6 votes vote down vote up
@PostMapping("/login")
@ResponseBody
public Result<Void> ajaxLogin(String username, String password) {
    UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
    Subject subject = SecurityUtils.getSubject();
    try {
        subject.login(token);
        return success();
    } catch (AuthenticationException e) {
        String msg = "用户或密码错误";
        if (StrUtil.isNotEmpty(e.getMessage())) {
            msg = e.getMessage();
        }
        return error(msg);
    }
}
 
Example #8
Source File: SysLoginController.java    From RuoYi with Apache License 2.0 6 votes vote down vote up
@PostMapping("/login")
@ResponseBody
public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) {
    UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
    Subject subject = SecurityUtils.getSubject();
    try {
        subject.login(token);
        return success();
    } catch (AuthenticationException e) {
        String msg = "用户或密码错误";
        if (StrUtil.isNotEmpty(e.getMessage())) {
            msg = e.getMessage();
        }
        return error(msg);
    }
}
 
Example #9
Source File: ShiroDialectTest.java    From thymeleaf-extras-shiro with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrincipalWithType() {
    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:"));
    assertFalse(result.contains("TYPEPRINCIPAL1"));
    assertFalse(result.contains("TYPEPRINCIPAL2"));

    // Logged in user
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertEquals(Integer.valueOf(0), SecurityUtils.getSubject().getPrincipals().oneByType(Integer.class)); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("TYPEPRINCIPAL1<span>0</span>TYPEPRINCIPAL1"));
    assertTrue(result.contains("TYPEPRINCIPAL20TYPEPRINCIPAL2"));
    subjectUnderTest.logout();
}
 
Example #10
Source File: AuthController.java    From Spring-Shiro-Spark with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: MyCustomRealm.java    From tutorials with MIT License 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
  throws AuthenticationException {

    UsernamePasswordToken uToken = (UsernamePasswordToken) token;

    if(uToken.getUsername() == null
      || uToken.getUsername().isEmpty()
      || !credentials.containsKey(uToken.getUsername())
      ) {
        throw new UnknownAccountException("username not found!");
    }


    return new SimpleAuthenticationInfo(
      uToken.getUsername(), credentials.get(uToken.getUsername()),
      getName());
}
 
Example #12
Source File: CurrentPasswordValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value != null) {
		AuthenticationToken token = new UsernamePasswordToken(SecurityUtils.getUser().getName(), value);
		try {
			if (SecurityUtils.getSecurityManager().authenticate(token) != null)
				return true;
		} catch (Exception e) {
		}
		constraintContext.disableDefaultConstraintViolation();
		constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
		return false;
	} else {
		return true;
	}
}
 
Example #13
Source File: ShiroHelloWorldTest.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void helloWorld() {
    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager manager = factory.getInstance();
    SecurityUtils.setSecurityManager(manager);
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");

    try {
        subject.login(token);
    } catch (AuthenticationException e) {
        LOG.error("Authentication Invalid: " + e.getMessage());
    }

    Assert.assertEquals(true, subject.isAuthenticated());

    subject.logout();
}
 
Example #14
Source File: LoginController.java    From ssm with Apache License 2.0 6 votes vote down vote up
@GetMapping("/login")
	public Msg login(HttpServletRequest request,
	                 @ApiParam(defaultValue = "wan2")@RequestParam("account") String account,
	                 @ApiParam(defaultValue = "123")@RequestParam("password") String password) throws Exception {
//		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		Subject subject = SecurityUtils.getSubject();
		System.out.println("喵喵喵");
		UsernamePasswordToken token = new UsernamePasswordToken(account, password);
		subject.login(token);
		return Msg.success("登陆成功");
//		if (exceptionClassName!=null){
//			if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
//				//最终会抛给异常处理器
//				throw new IException("账号不存在");
//			} else if (IncorrectCredentialsException.class.getName().equals(
//					exceptionClassName)) {
//				throw new IException("用户名/密码错误");
//			} else if("randomCodeError".equals(exceptionClassName)){
//				throw new IException("验证码错误");
//			} else{
//				throw new Exception();//最终在异常处理器生成未知错误
//			}
//		}
	}
 
Example #15
Source File: PasswordRealmMixin.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token )
    throws AuthenticationException
{
    UnitOfWork uow = uowf.newUnitOfWork();
    try
    {

        String username = ( (UsernamePasswordToken) token ).getUsername();
        PasswordSecurable account = findPasswordSecurable( uow, username );
        if( account == null )
        {
            LOG.debug( "Unknown subject identifier: {}" + username );
            return null;
        }
        LOG.debug( "Found account for {}: {}", username, account );
        return new SimpleAuthenticationInfo( account.subjectIdentifier().get(), account.password()
            .get(), getName() );
    }
    finally
    {
        uow.discard();
    }
}
 
Example #16
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 #17
Source File: PamRealmTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoGetAuthenticationInfo() {
  PamRealm realm = new PamRealm();
  realm.setService("sshd");

  String pamUser = System.getenv("PAM_USER");
  String pamPass = System.getenv("PAM_PASS");
  assumeTrue(pamUser != null);
  assumeTrue(pamPass != null);

  // mock shiro auth token
  UsernamePasswordToken authToken = mock(UsernamePasswordToken.class);
  when(authToken.getUsername()).thenReturn(pamUser);
  when(authToken.getPassword()).thenReturn(pamPass.toCharArray());
  when(authToken.getCredentials()).thenReturn(pamPass);

  AuthenticationInfo authInfo = realm.doGetAuthenticationInfo(authToken);

  assertTrue(authInfo.getCredentials() != null);
}
 
Example #18
Source File: AdminAuthController.java    From mall with MIT License 6 votes vote down vote up
@PostMapping("/login")
public Object login(@RequestBody String body) {
    String username = JacksonUtil.parseString(body, "username");
    String password = JacksonUtil.parseString(body, "password");

    if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
        return ResponseUtil.badArgument();
    }

    Subject currentUser = SecurityUtils.getSubject();
    try {
        currentUser.login(new UsernamePasswordToken(username, password));
    } catch (UnknownAccountException uae) {
        return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确");
    } catch (LockedAccountException lae) {
        return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用");

    } catch (AuthenticationException ae) {
        return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, ae.getMessage());
    }
    return ResponseUtil.ok(currentUser.getSession().getId());
}
 
Example #19
Source File: CredentialsMatcher.java    From OneBlog with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    UsernamePasswordToken utoken = (UsernamePasswordToken) token;
    //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
    String inPassword = new String(utoken.getPassword());
    //获得数据库中的密码
    String dbPassword = (String) info.getCredentials();
    try {
        dbPassword = PasswordUtil.decrypt(dbPassword, utoken.getUsername());
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    //进行密码的比对
    return this.equals(inPassword, dbPassword);
}
 
Example #20
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 #21
Source File: PageController.java    From JavaQuarkBBS with Apache License 2.0 6 votes vote down vote up
/**
 * 用户登录
 * @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";
    }
}
 
Example #22
Source File: SystemController.java    From express-ssm with Apache License 2.0 6 votes vote down vote up
/**
 * 登陆
 * @author jitwxs
 * @since 2018/5/2 0:02
 */
@PostMapping("/login")
public Msg login(SysUser user) {
    //Shiro实现登录
    UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
    Subject subject = SecurityUtils.getSubject();

    try {
        //如果获取不到用户名就是登录失败,但登录失败的话,会直接抛出异常
        subject.login(token);
    } catch (Exception e) {
        return Msg.error("用户名或密码错误");
    }

    //所有用户均重定向对应的展示配送页面
    if (subject.hasRole(RoleEnum.ADMIN.getName())) {
        return Msg.ok(null,"/admin/express");
    } else if (subject.hasRole(RoleEnum.STAFF.getName())) {
        return Msg.ok(null,"/staff/home");
    }

    return Msg.error("授权失败");
}
 
Example #23
Source File: ShiroRealm.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@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;
	}
 
Example #24
Source File: AuthenticatingRealmImplTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCreateWithPassowrd() throws Exception {
  buildTestAuthenticationConfig(CUser.STATUS_ACTIVE);

  String clearPassword = "default-password";
  String username = "testCreateWithPassowrdEmailUserId";

  CUser user = user("testCreateWithPassowrdEmail@somewhere", "testCreateWithPassowrdEmail",
      "testCreateWithPassowrdEmail", CUser.STATUS_ACTIVE, username, null);

  Set<String> roles = new HashSet<String>();
  roles.add("role");

  configurationManager.createUser(user, clearPassword, roles);

  UsernamePasswordToken upToken = new UsernamePasswordToken("testCreateWithPassowrdEmailUserId", clearPassword);
  AuthenticationInfo ai = realm.getAuthenticationInfo(upToken);
  String password = new String((char[]) ai.getCredentials());

  assertThat(passwordService.passwordsMatch(clearPassword, password), is(true));
}
 
Example #25
Source File: ActiveDirectoryGroupRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for
 * the specified username.  This method binds to the LDAP server using the provided username
 * and password - which if successful, indicates that the password is correct.
 * <p/>
 * This method can be overridden by subclasses to query the LDAP server in a more complex way.
 *
 * @param token              the authentication token provided by the user.
 * @param ldapContextFactory the factory used to build connections to the LDAP server.
 * @return an {@link AuthenticationInfo} instance containing information retrieved from LDAP.
 * @throws NamingException if any LDAP errors occur during the search.
 */
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
        LdapContextFactory ldapContextFactory) throws NamingException {
  UsernamePasswordToken upToken = (UsernamePasswordToken) token;

  // Binds using the username and password provided by the user.
  LdapContext ctx = null;
  try {
    String userPrincipalName = upToken.getUsername();
    if (!isValidPrincipalName(userPrincipalName)) {
      return null;
    }
    if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
      userPrincipalName = upToken.getUsername() + this.principalSuffix;
    }
    ctx = ldapContextFactory.getLdapContext(
        userPrincipalName, upToken.getPassword());
  } finally {
    LdapUtils.closeContext(ctx);
  }

  return buildAuthenticationInfo(upToken.getUsername(), upToken.getPassword());
}
 
Example #26
Source File: CredentialsMatcher.java    From springboot-shiro with MIT License 6 votes vote down vote up
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    UsernamePasswordToken utoken = (UsernamePasswordToken) token;
    //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
    String inPassword = new String(utoken.getPassword());
    //获得数据库中的密码
    String dbPassword = (String) info.getCredentials();
    try {
        dbPassword = PasswordUtil.decrypt(dbPassword, utoken.getUsername());
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    //进行密码的比对
    return this.equals(inPassword, dbPassword);
}
 
Example #27
Source File: ShiroDialectTest.java    From thymeleaf-extras-shiro with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrincipalWithProperty() {
    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:"));
    assertFalse(result.contains("PROPPRINCIPAL1"));
    assertFalse(result.contains("PROPPRINCIPAL2"));

    // Logged in user
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertEquals(Integer.valueOf(0), SecurityUtils.getSubject().getPrincipals().oneByType(Integer.class)); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("PROPPRINCIPAL1<span>" + USER1.toUpperCase() + " " + USER1.toUpperCase() + "</span>PROPPRINCIPAL1"));
    assertTrue(result.contains("PROPPRINCIPAL2" + USER1.toUpperCase() + " " + USER1.toUpperCase() + "PROPPRINCIPAL2"));
    subjectUnderTest.logout();
}
 
Example #28
Source File: SecurityComponent.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@DirectMethod
@Timed
@ExceptionMetered
@Validate
public UserXO authenticate(@NotEmpty final String base64Username, @NotEmpty final String base64Password)
    throws Exception
{
  Subject subject = securitySystem.getSubject();

  // FIXME: Subject is not nullable, but we have code that checks for nulls, likely from testing setups, verify and simplify
  checkState(subject != null);

  try {
    subject.login(new UsernamePasswordToken(
        Strings2.decodeBase64(base64Username),
        Strings2.decodeBase64(base64Password),
        false
    ));
  }
  catch (Exception e) {
    throw new Exception("Authentication failed", e);
  }

  return getUser();
}
 
Example #29
Source File: CredentialsMatcher.java    From springboot-learn with MIT License 6 votes vote down vote up
@Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        System.out.println("=================CredentialsMatcher.doCredentialsMatch=================");
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;
        //获得用户输入的密码:(可以采用加盐(salt)的方式去检验)
        String inPassword = new String(utoken.getPassword());
        //获得数据库中的密码
        String dbPassword = (String) info.getCredentials();
        try {
//            dbPassword = PasswordUtil.decrypt(dbPassword, utoken.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        //进行密码的比对
        return this.equals(inPassword, dbPassword);
    }
 
Example #30
Source File: ShiroDialectTest.java    From thymeleaf-extras-shiro with Apache License 2.0 5 votes vote down vote up
@Test
public void testHasRole() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    setSubject(subjectUnderTest);

    Context context = new Context();
    context.setVariable("roleExpression", "roled");
    String result;

    // Guest user
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("HASROLE1"));
    assertFalse(result.contains("HASROLE2"));

    // 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:"));
    assertTrue(result.contains("HASROLE1"));
    assertTrue(result.contains("HASROLE2"));
    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:"));
    assertFalse(result.contains("HASROLE1"));
    assertFalse(result.contains("HASROLE2"));
    subjectUnderTest.logout();
}