SpringBoot 集成Shiro--官网

SpringBoot 集成Shiro--官网,第1张

Spring Web 项目中,Shiro是通过过滤器来控制Web请求的

首先将Shiro的 web-starter 依赖添加到应用程序的类路径中,推荐采用 Maven 和 Gradle

maven

gradle

然后提供一个 Realm 的实现

最后添加一个 ShiroFilterChainDefinition 到容器中,它指定了 URL 路径及其对应的过滤器链

完整示例参考 github

如果包含了前面的 shiro-spring-boot-web-starter ,则就会自动开启Shiro的注解支持

Shiro的注解可以在 @Controller 类中使用,如下

为了确保应用程序工作,至少需要一个 ShiroFilterChainDefinition ,并且其中至少包含了一个URL的过滤器链,要么配置所有的路径均可以匿名访问,要么就配置一个过滤器来过滤请求

只需提供一个 CacheManager 的 bean 即可开启缓存

同Web应用一样,需要先添加 shiro-spring-boot-starter 依赖,配置也一样

然后配置一个 realm

最后为了使得 SecurityUtils 方法生效,只需要使得 SecurityManager 的bean设置到 SecurityUtils 即可

接下来就可以像下面这样获取 Subject 了

完整示例参考 github

从来没接触过shiro Java安全框架,突然有一天需要要用用户登陆验证和用户角色权限的任务,而且是针对shiro 进行整合,开始收到任务,心都有点凉凉的。经过一轮的搜索,感觉没多大的收获。很多用户的角色都是写在xml配置文件中。觉得太不人性化了,想换个用户角色还得改xml我觉得这么强大的框架应该不可能这么狗血的存在。然后认真的看文档,发现真的是可以直接读取数据库的。我把我搭建的流程发布在此。有问题的可以交流交流。我写的也并不是正确的,只能参考参考。

1webxml的配置

<listener>

<listener-class>orgapacheshirowebenvEnvironmentLoaderListener</listener-class>

</listener>

<filter>

<filter-name>shiroFilter</filter-name>

<filter-class>orgapacheshirowebservletShiroFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>shiroFilter</filter-name>

<url-pattern>/</url-pattern>

</filter-mapping>

2shiroini配置

[main]

[filters]

#自定义realm

shiroAuthorizingRealm = comframesecurityShiroAuthorizingRealm

securityManagerrealm = $shiroAuthorizingRealm

# 声明一个自定义的用户校验拦截器

customFormAuthenticationFilter = comframesecurityCustomFormAuthenticationFilter

# 声明一个自定义的用户角色权限拦截器

customPermissionsAuthorizationFilter = comframesecurityCustomPermissionsAuthorizationFilter

#cache

shiroCacheManager = orgapacheshirocacheehcacheEhCacheManager

shiroCacheManagercacheManagerConfigFile = classpath:ehcachexml

securityManagercacheManager = $shiroCacheManager

#session

sessionDAO = orgapacheshirosessionmgteisEnterpriseCacheSessionDAO

sessionManager = orgapacheshirowebsessionmgtDefaultWebSessionManager

sessionManagersessionDAO = $sessionDAO

securityManagersessionManager = $sessionManager

securityManagersessionManagerglobalSessionTimeout = 1800000

securityManager = orgapacheshirowebmgtDefaultWebSecurityManager

[urls]

/admin/user/login = anon

/admin/user/logout = anon

/admin/user/registered = anon

/admin/ = customFormAuthenticationFilter,customPermissionsAuthorizationFilter

从shiroini配置中可以看出,需要三个文件,分别为ShiroAuthorizingRealmjava(realm文件),CustomFormAuthenticationFilterjava(自定义用户登陆验证文件),CustomPermissionsAuthorizationFilter(自定义用户角色权限文件);

在urls配置中可以看出不需要拦截的url后面加上anon便可,但有先后顺序。

缓存是使用ehcache

3ehcachexml配置

<cache name="defaultCache" maxElementsInMemory="500"

maxElementsOnDisk="10000000" eternal="true" overflowToDisk="true"

diskSpoolBufferSizeMB="50" />

<cache name="shiro-activeSessionCache" maxElementsInMemory="500"

maxElementsOnDisk="10000000" eternal="true" overflowToDisk="true"

diskSpoolBufferSizeMB="50" />

<cache name="jdbcRealmauthorizationCache" maxElementsInMemory="500"

maxElementsOnDisk="10000000" eternal="true" overflowToDisk="true"

diskSpoolBufferSizeMB="50" />

<cache name="authorization" maxElementsInMemory="500"

timeToLiveSeconds="3600" eternal="false" overflowToDisk="false" />

4ShiroAuthorizingRealmjava

public class ShiroAuthorizingRealm extends AuthorizingRealm {

private AuthorityService authorityService = FrameContextgetBean(AuthorityServiceclass);

@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

Systemoutprintln("=======doGetAuthenticationInfo=======");

UsernamePasswordToken userToken = (UsernamePasswordToken) token;

String username = userTokengetUsername();

String password = StringvalueOf(userTokengetPassword());

User user = UserdaofindFirst("select from m_user where account = ", username);

if (user != null) {//下面可以做一些登陆的 *** 作,密码错误,用户状态等等

if(MD5EncodervalidPassword(password, usergetPassword())==false){

throw new UnknownAccountException();

}

SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());

return info;

} else {

return null;

}

}

@Override

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

Systemoutprintln("=======doGetAuthorizationInfo=======");

User user = (User) principalsgetPrimaryPrincipal();

if(user!=null){//从数据库中读取用户的角色权限,

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

List<String> perms = authorityServicegetUrlByUser(user);

if(perms!=null&&permssize()>0){//调用addStringPermissions方法把用户的权限信息添加到info中,可以addRoles方法把用户的角色添加到了info中

infoaddStringPermissions(perms);

}

return info;

}

return null;

}

}

5CustomFormAuthenticationFilterjava

public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

private final static Logger log = LoggergetLogger(CustomFormAuthenticationFilterclass);

private static final String contentType = "application/json; charset=UTF-8";

protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

>

这个就在在人员表了添加一个身份的字段 user_rank ,用这个来控制。用户登录到时候就会用登录信息,把这个 user_rank 字段带出来,在页面或者链接时候加上判断,哈这是简单的,看下官方的。

shiro安全框架是目前为止作为登录注册最常用的框架,因为它十分的强大简单,提供了认证、授权、加密和会话管理等功能 。

shiro能做什么?

认证:验证用户的身份

授权:对用户执行访问控制:判断用户是否被允许做某事

会话管理:在任何环境下使用 Session API,即使没有 Web 或EJB 容器。

加密:以更简洁易用的方式使用加密功能,保护或隐藏数据防止被偷窥

Realms:聚集一个或多个用户安全数据的数据源

单点登录(SSO)功能。

为没有关联到登录的用户启用 "Remember Me“ 服务

Shiro 的四大核心部分

Authentication(身份验证):简称为“登录”,即证明用户是谁。

Authorization(授权):访问控制的过程,即决定是否有权限去访问受保护的资源。

Session Management(会话管理):管理用户特定的会话,即使在非 Web 或 EJB 应用程序。

Cryptography(加密):通过使用加密算法保持数据安全

shiro的三个核心组件: 

Subject :正与系统进行交互的人,或某一个第三方服务。所有 Subject 实例都被绑定到(且这是必须的)一个SecurityManager 上。

SecurityManager:Shiro 架构的心脏,用来协调内部各安全组件,管理内部组件实例,并通过它来提供安全管理的各种服务。当 Shiro 与一个 Subject 进行交互时,实质上是幕后的 SecurityManager 处理所有繁重的 Subject 安全 *** 作。

Realms :本质上是一个特定安全的 DAO。当配置 Shiro 时,必须指定至少一个 Realm 用来进行身份验证和/或授权。Shiro 提供了多种可用的 Realms 来获取安全相关的数据。如关系数据库(JDBC),INI 及属性文件等。可以定义自己 Realm 实现来代表自定义的数据源。

shiro整合SSM框架:

1加入 jar 包:以下jar包自行百度下载

2配置 webxml 文件

在webxml中加入以下代码—shiro过滤器。

<filter>

<filter-name>shiroFilter</filter-name>

<filter-class>orgspringframeworkwebfilterDelegatingFilterProxy</filter-class>

<init-param>

<param-name>targetFilterLifecycle</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>shiroFilter</filter-name>

<url-pattern>/</url-pattern>

</filter-mapping>

3在 Spring 的配置文件中配置 Shiro

Springmvc配置文件中:<bean class="orgspringframeworkaopframeworkautoproxyDefaultAdvisorAutoProxyCreator"

depends-on="lifecycleBeanPostProcessor"/>

<bean class="orgapacheshirospringsecurityinterceptorAuthorizationAttributeSourceAdvisor">

<property name="securityManager" ref="securityManager"/>

</bean>

Spring配置文件中导入shiro配置文件:

<!-- 包含shiro的配置文件 -->

<import resource="classpath:applicationContext-shiroxml"/>

新建applicationContext-shiroxml

<xml version="10" encoding="UTF-8"><beans xmlns=">

导入ehcache-shiroxml配置文件:

<!--

~ Licensed to the Apache Software Foundation (ASF) under one

~ or more contributor license agreements  See the NOTICE file

~ distributed with this work for additional information

~ regarding copyright ownership  The ASF licenses this file

~ to you under the Apache License, Version 20 (the

~ "License"); you may not use this file except in compliance

~ with the License  You may obtain a copy of the License at

~

~     >

准备好了,接下来要写Realm方法了,新建shiro包,在包下新建MyRealmjava文件继承AuthorizingRealm

package shiro;import orgapacheshiroauthcAuthenticationException;import orgapacheshiroauthcAuthenticationInfo;import orgapacheshiroauthcAuthenticationToken;import orgapacheshiroauthcSimpleAuthenticationInfo;import orgapacheshiroauthccredentialHashedCredentialsMatcher;import orgapacheshiroauthzAuthorizationInfo;import orgapacheshiroauthzSimpleAuthorizationInfo;import orgapacheshirocryptohashMd5Hash;import orgapacheshirocryptohashSimpleHash;import orgapacheshirorealmAuthorizingRealm;import orgapacheshirosubjectPrincipalCollection;import orgapacheshiroutilByteSource;import orgspringframeworkbeansfactoryannotationAutowired;import beanuser;import daouserdao;public class MyRealm extends AuthorizingRealm {

@Autowired    private userdao userdao;

String pass;    /

授权:

/

@Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

Object principal = principalCollectiongetPrimaryPrincipal();//获取登录的用户名

if("admin"equals(principal)){               //两个if根据判断赋予登录用户权限

infoaddRole("admin");

}        if("user"equals(principal)){

infoaddRole("list");

}

infoaddRole("user");

return info;

}    /

用户验证

/

@Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

//1 token 中获取登录的 username! 注意不需要获取password

Object principal = tokengetPrincipal();

//2 利用 username 查询数据库得到用户的信息

user user=userdaofindbyname((String) principal);        if(user!=null){

pass=usergetPass();

}

String credentials = pass;        //3设置盐值 ,(加密的调料,让加密出来的东西更具安全性,一般是通过数据库查询出来的。 简单的说,就是把密码根据特定的东西而进行动态加密,如果别人不知道你的盐值,就解不出你的密码)

String source = "abcdefg";

ByteSource credentialsSalt = new Md5Hash(source);

//当前 Realm 的name

String realmName = getName();        //返回值实例化

SimpleAuthenticationInfo info =

new SimpleAuthenticationInfo(principal, credentials,

credentialsSalt, realmName);

return info;

}    //init-method 配置

public void setCredentialMatcher(){

HashedCredentialsMatcher  credentialsMatcher = new HashedCredentialsMatcher();

credentialsMatchersetHashAlgorithmName("MD5");//MD5算法加密

credentialsMatchersetHashIterations(1024);//1024次循环加密

setCredentialsMatcher(credentialsMatcher);

}

//用来测试的算出密码password盐值加密后的结果,下面方法用于新增用户添加到数据库 *** 作的,我这里就直接用main获得,直接数据库添加了,省时间

public static void main(String[] args) {

String saltSource = "abcdef";

String hashAlgorithmName = "MD5";

String credentials = "passwor";

Object salt = new Md5Hash(saltSource);        int hashIterations = 1024;

Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);

Systemoutprintln(result);

}

}

好了,接下来我们写一个简单的action来通过shiro登录验证。

//登录认证

   @RequestMapping("/shiro-login")    public String login(@RequestParam("username") String username,

           @RequestParam("password") String password){

       Subject subject = SecurityUtilsgetSubject();

       UsernamePasswordToken token = new UsernamePasswordToken(username, password);        

       try {            //执行认证 *** 作             subjectlogin(token);

       }catch (AuthenticationException ae) {

           Systemoutprintln("登陆失败: " + aegetMessage());            return "/index";

       }        

       return "/shiro-success";

   }

//温馨提示:记得在注册中密码存入数据库前也记得加密哦,提供一个utils方法//进行shiro加密,返回加密后的结果public static String md5(String pass){

String saltSource = "blog";    

String hashAlgorithmName = "MD5";

Object salt = new Md5Hash(saltSource);int hashIterations = 1024;    

Object result = new SimpleHash(hashAlgorithmName, pass, salt, hashIterations);

String password = resulttoString();return password;

}

好了,shiro登录验证到这里完了

1、Shiro默认的Session处理方式

<!-- 定义 Shiro 主要业务对象 -->

<bean id="securityManager" class="orgapacheshirowebmgtDefaultWebSecurityManager">

<!-- <property name="sessionManager" ref="sessionManager" /> -->

<property name="realm" ref="systemAuthorizingRealm" />

<property name="cacheManager" ref="shiroCacheManager" />

</bean>

这里从DefaultWebSecurityManager这里看起,这个代码是定义的Shiro安全管理对象,看下面的构造方法(代码 1-1)

(代码 1-1)

public DefaultWebSecurityManager() {

super();

((DefaultSubjectDAO) thissubjectDAO)setSessionStorageEvaluator(new DefaultWebSessionStorageEvaluator());

thissessionMode = >

以上就是关于SpringBoot 集成Shiro--官网全部的内容,包括:SpringBoot 集成Shiro--官网、如何正确的使用shiro、ssm框架访问控制应该怎么做等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9571071.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-29
下一篇2023-04-29

发表评论

登录后才能评论

评论列表(0条)

    保存