前后端分离项目中SpringBoot整合Shiro

在前后端分离项目中,前端使用Angular,后端使用SpringBoot整合Shiro。

1.SpringBoot的设置

SpringBoot添加跨域设置


@SpringBootApplication
public class PostfinanceApplication {

	@Configuration
	@EnableWebMvc
	public class WebMvcConfg implements WebMvcConfigurer {

		@Override
		public void addCorsMappings(CorsRegistry registry) {
			WebMvcConfigurer.super.addCorsMappings(registry);
			registry.addMapping("/**")//需要跨域访问的Map路径
			.allowedOrigins("http://localhost:4200")//允许跨域访问的ip及端口
			.allowedHeaders("*")//允许跨域访问的Headers内容
			.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")//允许跨域访问的方法,OPTIONS必须设置Shiro中用到
			.allowCredentials(true);
		}
	}

	public static void main(String[] args) {
		SpringApplication.run(PostfinanceApplication.class, args);
	}
}

2.Shiro的设置

现代浏览器在进行跨域请求时会先发送一条OPTIONS方法的请求,验证服务器是否支持跨域,随后发放正式请求获取相应数据。
Shiro默认会对所有请求进行验证,因此第一条OPTIONS请求会返回失败,浏览器据此认定服务器不支持跨域,不再进行第二次的正式请求。因此需要配置Shiro的拦截器fiter中对第一条OPTIONS方法的请求进行放行
。具体功能在MyPassThruAuthenticationFilter的onPreHandle方法中。第一条OPTIONS请求执行成功,浏览器接着发送正式请求获取数据。
如果正式请求为非法访问(未登录)时,Shiro会对请求进行重定向到设置的loginUrl,若不设置默认loginUrl则重定向到login.jsp。
在重定向过程中Shiro会清空请求头内的所有信息,再次引起跨域问题,此时需要在拦截器内重新设置请求头:MyPassThruAuthenticationFilter的onAccessDenied方法。

1.整体ShiroConfig的配置

package xyz.linkq.postfinance.sec.shiro;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ShiroConfig {

	/**
	 * 请求拦截
	 * @param securityManager
	 * @return
	 */
	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		Map<String, Filter> filtersMap = new HashMap<>();
		MyPassThruAuthenticationFilter authFilter = new MyPassThruAuthenticationFilter();
		filtersMap.put("authc", authFilter);
		shiroFilterFactoryBean.setFilters(filtersMap);
		// 拦截器.
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
		filterChainDefinitionMap.put("/login", "anon");
		filterChainDefinitionMap.put("/**", "authc");
		shiroFilterFactoryBean.setLoginUrl("/unauth");
		/*
		 * 注意过滤器配置顺序 不能颠倒 
		 * anon. 配置不会被拦截的请求 顺序判断
		 * authc. 配置拦截的请求
		 * 配置shiro默认登录界面地址,前后端分离中登录界面跳转应由前端路由控制,后台仅返回json数据
         * 所有非法请求被重定向到/unauth,该请求返回一个json数据
		 * shiroFilterFactoryBean.setLoginUrl("/unauth");
		 */
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		return shiroFilterFactoryBean;
	}

	/**
	 * @Title: securityManager
	 * @Description: SecurityManager,权限管理,这个类组合了登陆,登出,权限,session的处理
	 * @return SecurityManager
	 */
	@Bean
	public SecurityManager securityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(myShiroRealm());
		securityManager.setSessionManager(sessionManager());
		return securityManager;
	}

	/**
	 * 自定义认证
	 * @Title: myShiroRealm
	 * @Description: ShiroRealm,这是个自定义的认证类,继承自AuthorizingRealm,负责用户的认证和权限的处理
	 * @return MyShiroRealm
	 */
	@Bean
	public MyShiroRealm myShiroRealm() {
		MyShiroRealm myShiroRealm = new MyShiroRealm();
		myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
		return myShiroRealm;
	}

	/**
	 * 密码凭证匹配器,作为自定义认证的基础 (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了 )
	 * 
	 * @return
	 */
	@Bean
	public HashedCredentialsMatcher hashedCredentialsMatcher() {
		HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
		hashedCredentialsMatcher.setHashAlgorithmName("MD5");// 散列算法:这里使用MD5算法;
		hashedCredentialsMatcher.setHashIterations(1024);// 散列的次数,比如散列两次,相当于 md5(md5(""));
		hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
		return hashedCredentialsMatcher;
	}

	/**
	 * 自定义sessionManager,用户的唯一标识,即Token或Authorization的认证
	 */
	@Bean
	public SessionManager sessionManager() {
		MySessionManager mySessionManager = new MySessionManager();
		return mySessionManager;
	}

}
  1. MySessionManager

MySessionManage的作用是从后端服务器收到的请求头中根据Authorization获取SessionID

package xyz.linkq.postfinance.sec.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class MySessionManager extends DefaultWebSessionManager {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String AUTHORIZATION = "Authorization";
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
    
    public MySessionManager() {  
        super();  
    }  
  
    @Override  
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {  
    	//前端ajax的headers中必须传入Authorization的值
        String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION); 
        //如果请求头中有 Authorization 则其值为sessionId  
        if (!StringUtils.isEmpty(id)) {  
        	request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);  
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE); 
            logger.info("调用MySessionManager获取sessionId="+id);
            return id;  
        } else {  
            //否则按默认规则从cookie取sessionId  
            logger.info("调用MySessionManager使用默认模式从cookie获取sessionID为"+id);
            return super.getSessionId(request, response);  
        }  
    }  
}

3.过滤器MyPassThruAuthenticationFilter

在ShiroConfig配置类的shiroFilter方法中配置使用MyPassThruAuthenticationFilter过滤器
系统重定向会默认把请求头清空,通过在MyPassThruAuthenticationFilter的onAccessDenied方法中重新设置请求头,解决跨域问题 。当Shiro判定当前请求为非法请求(未登录)时,会调用该onAccessDenied方法,若当前请求地址是设定的loginUrl则放行继续执行之后的方法,在我们的配置中是执行/unauth请求的方法,返回json数据。若当前请求不是loginUrl方法则重定向到loginUrl方法。

package xyz.linkq.postfinance.sec.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

public class MyPassThruAuthenticationFilter extends PassThruAuthenticationFilter {

	private Logger log = LoggerFactory.getLogger(this.getClass());

        //获取请求方法,若为OPTIONS请求直接返回True放行
	@Override
	public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

		log.info("进入MyPassThruAuthenticationFilter");

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
			log.info("OPTIONS方法直接返回True");
			return true;
		}
		return super.onPreHandle(request, response, mappedValue);
	}
	
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletResponse httpResp = WebUtils.toHttp(response);
		HttpServletRequest httpReq = WebUtils.toHttp(request);

		/** 系统重定向会默认把请求头清空,这里通过拦截器重新设置请求头,解决跨域问题 */
		httpResp.addHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));
		httpResp.addHeader("Access-Control-Allow-Headers", "*");
		httpResp.addHeader("Access-Control-Allow-Methods", "*");
		httpResp.addHeader("Access-Control-Allow-Credentials", "true");

		if (isLoginRequest(request, response)) {
			return true;
		} else {
			saveRequestAndRedirectToLogin(request, response);
			return false;
		}
	}
}

3.Angular中的配置

前端发送登录请求进行登录后,服务器返回当前登录的sessionId,前端获取到sessionId之后保存到sessionStorage中

{"resultCode":"SUCCESS","data":{"sessionId":"3ab87ebe-df53-4054-b9f6-996ce5c8aa7c"},"message":"登录成功!"}
sessionStorage.setItem("sessionId",data.data.sessionId)

登录后向服务器发送请求时需添加Authorization请求头并设置withCredentials为true

   httpOptions = {
    headers: new HttpHeaders({
      'Authorization': sessionStorage.getItem("sessionId")
    }),
    withCredentials:true
  };
  public getDailyReportDatas(): Observable<any> {

    return this.hc.get(this.apiURL.dailyreportdatas,this.httpOptions);

  }

若请求为未登录状态则返回前端重定向到登录页
Angular中页面跳转

        if(datas.resultCode=="FAIL"){
          alert(datas.message);
          this.router.navigateByUrl("/login")
          return;
        }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值