日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Apache Shiro实现用户登录功能

發布時間:2025/1/21 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Apache Shiro实现用户登录功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

apache shiro實現用戶登錄功能

配置shiro的Filter實現URL級別權限控制

配置web.xml

<!-- shiro的過濾器 --> <filter><!-- 應用配置后將會去spring的配置文件中尋找與shiroFilter同名的bean --><filter-name>shiroFilter</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping><filter-name>shiroFilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping>

配置applicationContext-shiro.xml,并在applicationContext.xml中引入applicationContext-shiro.xml。

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"><!-- 配置Shiro核心Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><!-- 安全管理器 --><property name="securityManager" ref="securityManager" /><!-- 未認證,跳轉到哪個頁面 --><property name="loginUrl" value="/login.html" /><!-- 登錄頁面頁面 --><property name="successUrl" value="/index.html" /><!-- 認證后,沒有權限跳轉頁面 --><property name="unauthorizedUrl" value="/unauthorized.html" /><!-- shiro URL控制過濾器規則 --><property name="filterChainDefinitions"><value>/login.html* = anon/user_login.action* = anon /validatecode.jsp* = anon/css/** = anon/js/** = anon/images/** = anon/services/** = anon /pages/base/courier.html* = perms[courier:list]/pages/base/area.html* = roles[base]/** = authc</value></property> </bean><!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="bosRealm" /><property name="cacheManager" ref="shiroCacheManager" /> </bean><!-- 配置Realm --> <bean id="bosRealm" class="cn.niwotaxuexiba.bos.realm.BosRealm"><!-- 緩存區的名字 就是 ehcache.xml 自定義 cache的name --><property name="authorizationCacheName" value="bos" /> </bean><bean id="lifecycleBeanPostProcessor"class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/><!-- 開啟shiro注解模式 --> <beanclass="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"depends-on="lifecycleBeanPostProcessor" ><property name="proxyTargetClass" value="true" /> </bean><bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"><property name="securityManager" ref="securityManager"/> </bean></beans>

在applicationContext.xml中引入applicationContext-shiro.xml

<!-- 引入shiro的配置 --> <import resource="applicationContext-shiro.xml"/>

前端頁面代碼編寫

設置form表單的action

<form class="form-horizontal" id="loginform" name="loginform" method="post" action="user_login.action>... </form>

點擊立即登錄按鈕,提交form表單

<a href="javascript:$('#loginform').submit();" class="btn btn-danger" target="_blank">立即登錄 </a>

后臺Java代碼實現

編寫UserAction,提供login登錄方法

@Namespace("/") @ParentPackage("json-default") @Controller @Scope("prototype") public class UserAction extends BaseAction<User> {@Action(value = "user_login", results = {@Result(name = "login", type = "redirect", location = "login.html"),@Result(name = "success", type = "redirect", location = "index.html") })public String login() {// 用戶名和密碼 都保存在model中// 基于shiro實現登錄Subject subject = SecurityUtils.getSubject();// 用戶名和密碼信息AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());try {subject.login(token);// 登錄成功// 將用戶信息 保存到 Sessionreturn SUCCESS;} catch (AuthenticationException e) {// 登錄失敗e.printStackTrace();return LOGIN;}} }

shiro的執行流程是:應用程序–>Subject–>SecurityManager–>Realm–>安全數據

自定義Realm對象,實現認證方法。自定義的Realm接口需要集成AuthorizingRealm接口。

//自定義的Realm,實現 安全數據的連接 @Service("bosRealm") public class BosRealm extends AuthorizingRealm {@Autowiredprivate UserService userService;@Override//授權protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {System.out.println("shiro 授權管理...");return null;}@Override// 認證...protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("shiro 認證管理... ");// 轉換tokenUsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;// 根據用戶名 查詢 用戶信息User user = userService.findByUsername(usernamePasswordToken.getUsername());if (user == null) {// 用戶名不存在// 參數一: 期望登錄后,保存在Subject中信息// 參數二: 如果返回為null 說明用戶不存在,報用戶名// 參數三 :realm名稱return null;} else {// 用戶名存在// 當返回用戶密碼時,securityManager安全管理器,自動比較返回密碼和用戶輸入密碼是否一致// 如果密碼一致 登錄成功, 如果密碼不一致 報密碼錯誤異常return new SimpleAuthenticationInfo(user, user.getPassword(),getName());}}}

將自定義的Realm注入到安全管理器SecurityManager中。

<!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="bosRealm" /><property name="cacheManager" ref="shiroCacheManager" /> </bean>

service代碼

@Service @Transactional public class UserServiceImpl implements UserService {@Autowiredprivate UserRepository userRepository;@Overridepublic User findByUsername(String username) {return userRepository.findByUsername(username);}}

dao代碼

public interface UserRepository extends JpaRepository<User, Integer> {User findByUsername(String username);}

在shiroFilter中將user_login.action放行

<!-- shiro URL控制過濾器規則 --> <property name="filterChainDefinitions"><value>/login.html* = anon/user_login.action* = anon<!-- 放行 --> /validatecode.jsp* = anon/css/** = anon/js/** = anon/images/** = anon/services/** = anon /pages/base/courier.html* = perms[courier:list]/pages/base/area.html* = roles[base]/** = authc</value> </property>

總結

以上是生活随笔為你收集整理的Apache Shiro实现用户登录功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。