shiro + springBoot扫码登陆

使用微信扫码登陆网站

        @Bean(name = "shiroFilter")
	public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("mapperRealm") MapperRealm mapperRealm) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager(mapperRealm));
		shiroFilterFactoryBean.setLoginUrl("/login");
		shiroFilterFactoryBean.setFilterChainDefinitions("/code = anon");
		shiroFilterFactoryBean.setSuccessUrl("/index");
		shiroFilterFactoryBean.setUnauthorizedUrl("/xxxx");


		Map filterChainDefinitionManager = new HashMap<>();
		filterChainDefinitionManager.put("/**", "anon");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager);
		return shiroFilterFactoryBean;

主要是这句:

shiroFilterFactoryBean.setFilterChainDefinitions("/code = anon");

意思是通过ajax请求访问的放行地址


@RequestMapping(value = "code", method = RequestMethod.GET)
	public ModelAndView code(HttpServletRequest request){
		String code = ServletRequestUtils.getStringParameter(request,"code","");
		String state = ServletRequestUtils.getStringParameter(request,"state","");

		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			MyToken token = new Mytoken();//继承UsernamePasswordToken
			token.setState(state);
			token.setCode(code);
            char[] chars = "code".toCharArray();
            token.setPassword(chars);//密码字段不能为空
            token.setRememberMe(false);

			try{
				currentUser.login(token);
			}catch(UnknownAccountException ex){
				logger.debug("账号错误");
			}catch(IncorrectCredentialsException ex){
				logger.debug("密码错误");
			}
			ModelAndView mv = new ModelAndView("index");
			return mv;
		}
		return null;
	}

自定义token类

public class Mytoken extends UsernamePasswordToken {

	private String code;
	private String state;

	public String getCode() {
		return code;
	}
	public String getState() {
		return state;
	}

	public void setCode(String code) {
		this.code = code;
	}
	public void setState(String state) {
		this.state = state;
	}

	public Mytoken(final String username, final String password, boolean rememberMe, final String host,
										final String code,final String state) {
		super(username, password, rememberMe, host);
		this.code = code;
		this.state = state;
	}

	public Mytoken() {
		super();
	}
	
}

最后在Realm类的doGetAuthenticationInfo方法中添加相关的验证方法,上面我们已经把微信转发过来的code存在token里了,这里只要在token中取出来校验是否存在就可以了

返回 return new SimpleAuthenticationInfo(User, token.getPassword(),getName());

你可能感兴趣的:(那些年踩过的坑)