Shiro的简单介绍
Shiro是Java的一个安全框架,旨在简化身份验证和授权。Shiro在JavaSE和JavaEE项目中都可以使用。它主要用来处理身份认证,授权,企业会话管理和加密等。
shiro由三部分组成:
1、Subject:当前操作的用户就是当前登录的用户;
2、SecurityMapper:该组件用来管理所有操作用户的安全操作
3、Realm:该组件需要自己来定义,shiro当前登录的账号、密码是否正确,并且其拥有那些权限
Shiro实现登录
1、pom文件配置
<!--shiro 用于登录--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.4.2</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.4.2</version></dependency>
2、创建realm包下的UserRealm类,
使其继承AuthorZingReal类,并在该UserRealm类下实现AuthorZingReal中的doGetAuthenticationInfo()和doGetAuthorizationInfo()方法 认证和授权
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(Authentication token) throws Exception{//获取用户QueryWapper<User> wapper=new QueryWapper<>();wapper.eq("username",token.getPrincipal.toString());User user=userService.getOne(wapper);//进行判断if(user!=null){//三个参数:账号、密码、用户名SimpleAuthentication simpleAuthenticationInfo=new SimpleAuthentication(user,user.getPassword,this.getName());return simpleAuthenticationInfo;}return null;
}//授权protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {return null;}
3、创建对应的configl类——ShiroConfig
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass(value = { SecurityManager.class })
@ConfigurationProperties(prefix = "shiro")
@Data
public class ShiroConfig {private static final String SHIRO_DIALECT = "shiroDialect";private static final String SHIRO_FILTER = "shiroFilter";// 加密方式private String hashAlgorithmName = "md5";// 散列次数private int hashIterations = 2;// 默认的登陆页面private String loginUrl = "/index.html";private String[] anonUrls; // 放行的路径private String logOutUrl; // 登出的地址private String[] authcUlrs; // 拦截的路径/*** 声明凭证匹配器*//*@Bean("credentialsMatcher")public HashedCredentialsMatcher hashedCredentialsMatcher() {HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();credentialsMatcher.setHashAlgorithmName(hashAlgorithmName);credentialsMatcher.setHashIterations(hashIterations);return credentialsMatcher;}*//*** 声明userRealm*/@Bean("userRealm")public UserRealm userRealm() {UserRealm userRealm = new UserRealm();return userRealm;}/*** 配置SecurityManager*/@Bean("securityManager")public SecurityManager securityManager(UserRealm userRealm) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();// 注入userRealmsecurityManager.setRealm(userRealm);return securityManager;}/*** 配置shiro的过滤器*/@Bean(SHIRO_FILTER)public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();// 设置安全管理器factoryBean.setSecurityManager(securityManager);// 设置未登陆的时要跳转的页面factoryBean.setLoginUrl(loginUrl);Map<String, String> filterChainDefinitionMap = new HashMap<>();// 设置放行的路径if (anonUrls != null && anonUrls.length > 0) {for (String anon : anonUrls) {filterChainDefinitionMap.put(anon, "anon");}}// 设置登出的路径if (null != logOutUrl) {filterChainDefinitionMap.put(logOutUrl, "logout");}// 设置拦截的路径if (authcUlrs != null && authcUlrs.length > 0) {for (String authc : authcUlrs) {filterChainDefinitionMap.put(authc, "authc");}}Map<String, Filter> filters=new HashMap<>();factoryBean.setFilters(filters);factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);return factoryBean;}/*** 注册shiro的委托过滤器,相当于之前在web.xml里面配置的* @return*/@Beanpublic FilterRegistrationBean<DelegatingFilterProxy> delegatingFilterProxy() {FilterRegistrationBean<DelegatingFilterProxy> filterRegistrationBean = new FilterRegistrationBean<DelegatingFilterProxy>();DelegatingFilterProxy proxy = new DelegatingFilterProxy();proxy.setTargetFilterLifecycle(true);proxy.setTargetBeanName(SHIRO_FILTER);filterRegistrationBean.setFilter(proxy);return filterRegistrationBean;}/* 加入注解的使用,不加入这个注解不生效--开始 *//**** @param securityManager* @return*/@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);return authorizationAttributeSourceAdvisor;}@Beanpublic DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();advisorAutoProxyCreator.setProxyTargetClass(true);return advisorAutoProxyCreator;}/* 加入注解的使用,不加入这个注解不生效--结束 *//*** 这里是为了能在html页面引用shiro标签,上面两个函数必须添加,不然会报错** @return*/@Bean(name = SHIRO_DIALECT)public ShiroDialect shiroDialect() {return new ShiroDialect();}}
这里基本不用改变,最重要的就是这三个路径:
private String[] anonUrls; // 放行的路径 private String logOutUrl; // 登出的地址 private String[] authcUlrs; // 拦截的路径
4、在yml文件中进行配置
#shiro的配置
shiro:anon-urls: #放行路径- /toLogin*- /login.html*- /login/login- /login/getCode- /css/**- /echarts/**- /images/**- /layui/**- /layui_ext/**- /js/**login-url: /index.html log-out-url: /login/logout* #登出路径authc-ulrs: #拦截路径- /**
5、在controller中进行登录和登出设置
//shiro登录
Subject subject = SecurityUtil.getSubject();
UsernamePasswordToken token=new UsernameToken(username,password);
subject.login(token);
User user=(User)suject.getPrincipal();
//shiro登出
@RequestMapping("/login/logout")
@ResponseBodypublic String logout(){Subject subject=SecurityUtil.getSubject();suject.logout();return "longin"; //返回到登录页面
}