SpringBoot整合SpringSecurity中自己踩过的坑

SpringBoot整合SpringSecurity中自己踩过的坑

使用用户自定义的UserDetailService进行用户身份认证

  1. SpringBoot扩展SpringSecurity资源授权中hasRole、hasAnyRole、hasAuthority等方法的参数不需要加ROLE_前缀,

    从数据库中查询出来的角色名没有ROLE_前缀则要加,并加入List

    private static String hasAnyRole(String... authorities) {
    		String anyAuthorities = StringUtils.arrayToDelimitedString(authorities,
    				"','ROLE_");
    		return "hasAnyRole('ROLE_" + anyAuthorities + "')";
    	}
    
    	private static String hasRole(String role) {
    		Assert.notNull(role, "role cannot be null");
    		if (role.startsWith("ROLE_")) {
    			throw new IllegalArgumentException(
    					"role should not start with 'ROLE_' since it is automatically inserted. Got '"
    							+ role + "'");
    		}
    		return "hasRole('ROLE_" + role + "')";
    	}
    
    	private static String hasAuthority(String authority) {
    		return "hasAuthority('" + authority + "')";
    	}
    
    	private static String hasAnyAuthority(String... authorities) {
    		String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','");
    		return "hasAnyAuthority('" + anyAuthorities + "')";
    	}
    

    查看源码可知,如果在授权时加了ROLE_前缀则会出异常

  2. loginPage和loginProcessingUrl的区别

    loginPage是指定登录页面的url或者是请求登录页的controller标识

    loginProcessingUrl是指定登录验证的标识符,这里springSecurity默认就是/login

    同理logoutUrl和logoutSuccessUrl,logoutUrl是指定登出的处理请求url,logoutSuccessUrl是登出成功后跳转的url

  3. /logout在没有禁用csrf跨域请求时必须是post请求,禁用后可以用get发起logout请求

    public boolean matches(HttpServletRequest request) {
            if (this.httpMethod != null && StringUtils.hasText(request.getMethod()) && this.httpMethod != valueOf(request.getMethod())) {
                
                //通过debug发现this.httpMethod的值是post,如果logout请求不是post,这里会返回为
                //false,则过滤器不能放行
                
                if (logger.isDebugEnabled()) {
                    logger.debug("Request '" + request.getMethod() + " " + this.getRequestPath(request) + "' doesn't match '" + this.httpMethod + " " + this.pattern + "'");
                }
    
                return false;
            } else if (this.pattern.equals("/**")) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Request '" + this.getRequestPath(request) + "' matched by universal pattern '/**'");
                }
    
                return true;
            } else {
                String url = this.getRequestPath(request);
                if (logger.isDebugEnabled()) {
                    logger.debug("Checking match of request : '" + url + "'; against '" + this.pattern + "'");
                }
    
                return this.matcher.matches(url);
            }
    
posted @ 2021-02-06 18:10  编程の小白  阅读(161)  评论(0编辑  收藏  举报