国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

spring secrity 自定義驗(yàn)證

2019-11-10 20:21:11
字體:
供稿:網(wǎng)友

sPRing secrity 驗(yàn)證默認(rèn)是使用username和passWord。但是我項(xiàng)目的登錄是根據(jù)用戶的   的工號和密碼進(jìn)行驗(yàn)證的,所有 有點(diǎn)不同。

關(guān)鍵點(diǎn)是 自己實(shí)現(xiàn)了   myAuthenticationProvider;

<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                          http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd"><global-method-security pre-post-annotations="enabled" /><!-- HTTP安全配置 --><http auto-config="false" entry-point-ref="authenticationEntryPoint"  access-denied-page="/denied.html"><intercept-url pattern="/login.html" access="IS_AUTHENTICATED_ANONYMOUSLY"/><intercept-url pattern="/index.html" access="IS_AUTHENTICATED_ANONYMOUSLY"/><intercept-url pattern="/m/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/><intercept-url pattern="/commons/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/><intercept-url pattern="/upload/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>        <intercept-url pattern="/cms/**" access="ROLE_USER"/>       <!--  <intercept-url pattern="/adminIndex.html" access="ROLE_USER"/> -->        <intercept-url pattern="/pages/*.html" access="ROLE_USER"/>       <!--  logout-success-url="/login.html" -->        <logout logout-url="/j_spring_security_logout" invalidate-session="true"             delete-cookies="JSESSIONID" success-handler-ref="myLogoutSuccessHandler"/>                <custom-filter ref="corsFilter" after="PRE_AUTH_FILTER"/><custom-filter ref="myLoginFilter" position="FORM_LOGIN_FILTER" /><custom-filter ref="mySecurityFilter" before="FILTER_SECURITY_INTERCEPTOR" /></http><beans:bean id="corsFilter" class="com.threeti.danfoss.base.filter.SecurityCorsFilter" /><beans:bean id="sas"class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy"><beans:property name="maximumSessions" value="1"></beans:property><beans:property name="exceptionIfMaximumExceeded"value="true"></beans:property><beans:constructor-arg name="sessionRegistry"ref="sessionRegistry"></beans:constructor-arg></beans:bean><beans:bean id="sessionRegistry"class="org.springframework.security.core.session.SessionRegistryImpl"></beans:bean><beans:bean id="myLoginFilter"class="com.threeti.danfoss.base.filter.MyUsernamePasswordAuthenticationFilter"><beans:property name="authenticationManager" ref="myAuthenticationManager"/>          <beans:property name="authenticationFailureHandler" ref="failureHandler"/>          <beans:property name="authenticationSuccessHandler" ref="successHandler"/>  <beans:property name="sessionAuthenticationStrategy"ref="sas"></beans:property></beans:bean>     <beans:bean id="successHandler" class="com.threeti.danfoss.base.handler.MyAuthenticationSuccessHandler">          <beans:property name="defaultTargetUrl" value="/pages/menu.html#current/wind/surface/level/anim=off/overlay=misery_index/orthographic=39.08,42.42,294/loc=96.475,39.357" />      </beans:bean>         <beans:bean id="failureHandler" class="com.threeti.danfoss.base.handler.MySimpleUrlAuthenticationFailureHandler">          <beans:property name="defaultFailureUrl" value="/index.html"/>      </beans:bean>         <beans:bean id="myLogoutSuccessHandler" class="com.threeti.danfoss.base.handler.MyLogoutSuccessHandler">        <beans:property name="defaultTargetUrl" value="/login.html"/>        <!-- 下面的 是通過在url參數(shù)進(jìn)行跳轉(zhuǎn) -->        <!-- <property name="targetUrlParameter" value="target-url"/>      <property name="redirectStrategy" ref="safeRedirectStrategy"/> -->    </beans:bean>     <!-- 安全的RedirectStrategy,主要是判斷跳轉(zhuǎn)地址是否在白名單中    public class SafeRedirectStrategy implements RedirectStrategy -->    <!-- <beans:bean id="safeRedirectStrategy" class="com.snsxiu.job.web.security.SafeRedirectStrategy"/> -->    <!-- 1.URL過濾器或方法攔截器:用來攔截URL或者方法資源對其進(jìn)行驗(yàn)證,其抽象基類為AbstractSecurityInterceptor 2.資源權(quán)限獲取器:用來取得訪問某個(gè)URL或者方法所需要的權(quán)限,接口為SecurityMetadataSource 3.訪問決策器:用來決定用戶是否擁有訪問權(quán)限的關(guān)鍵類,其接口為AccessDecisionManager 調(diào)用順序?yàn)椋篈bstractSecurityInterceptor調(diào)用SecurityMetadataSource取得資源的所有可訪問權(quán)限, 然后再調(diào)用AccessDecisionManager來實(shí)現(xiàn)決策,確定用戶是否有權(quán)限訪問該資源。 --><!-- 自定義的filter, 必須包含authenticationManager, accessDecisionManager, securityMetadataSource三個(gè)屬性 --><beans:bean id="mySecurityFilter" class="com.threeti.danfoss.base.security.XaFilterSecurityInterceptor"><beans:property name="authenticationManager" ref="myAuthenticationManager" /><beans:property name="accessDecisionManager" ref="myAccessDecisionManager" /><beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" /></beans:bean><!-- 取HTTP配置中的authenticationManager 設(shè)置alias別名 --><authentication-manager alias="myAuthenticationManager"><authentication-provider ref="myAuthenticationProvider"/></authentication-manager><!-- 用戶詳細(xì)信息管理:數(shù)據(jù)源、用戶緩存(通過數(shù)據(jù)庫管理用戶、角色、權(quán)限、資源) --><beans:bean id="userDetailsManager" class="com.threeti.danfoss.base.security.XaUserDetailsService"></beans:bean><!-- <beans:beanclass="org.springframework.security.authentication.encoding.md5PasswordEncoder"id="passwordEncoder"></beans:bean> --><beans:bean id="myAuthenticationProvider" class="com.threeti.danfoss.base.filter.MyAuthenticationProvider"><!-- <beans:property name="userDetailsService" ref="userDetailsManager"/> --><beans:constructor-arg name="userDetailsService" ref="userDetailsManager"/><!-- <beans:property name="passwordEncoder" ref="passwordEncoder"/> --></beans:bean><!-- 訪問決策器,決定某個(gè)用戶具有的角色,是否有足夠的權(quán)限去訪問某個(gè)資源。 --><beans:bean id="myAccessDecisionManager"class="com.threeti.danfoss.base.security.XaAccessDecisionManagerService" /><!-- 資源源數(shù)據(jù)定義,將所有的資源和權(quán)限對應(yīng)關(guān)系建立起來,即定義某一資源可以被哪些角色去訪問。 --><beans:bean id="mySecurityMetadataSource" init-method="loadResourceDefine"class="com.threeti.danfoss.base.security.XaSecurityMetadataSourceService"></beans:bean><beans:bean id="authenticationEntryPoint"class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"><beans:property name="loginFormUrl" value="/login.html" /></beans:bean></beans:beans>

這個(gè)是我實(shí)現(xiàn)的的  myAuthenticationProvider;

package com.threeti.danfoss.base.filter;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.AuthenticationProvider;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import com.threeti.danfoss.base.exception.LoginLockException;import com.threeti.danfoss.base.repository.XaCmsUserRepository;import com.threeti.danfoss.base.util.MD5Util;public class MyAuthenticationProvider implements AuthenticationProvider{@AutowiredXaCmsUserRepository xaCmsUserRepository;private UserDetailsService userDetailsService;      public MyAuthenticationProvider(UserDetailsService userDetailsService) {          this.userDetailsService = userDetailsService;      }    public UserDetailsService getUserDetailsService() {return userDetailsService;}public void setUserDetailsService(UserDetailsService userDetailsService) {this.userDetailsService = userDetailsService;}@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;          String username = token.getName();          //從數(shù)據(jù)庫找到的用戶          UserDetails userDetails = null;          if(username != null) {              userDetails = userDetailsService.loadUserByUsername(username);          }          //XaCmsUser user =xaCmsUserRepository.findByNumberAndPasswordAndStatus(userDetails.getUsername(),        //MD5Util.getMD5String(userDetails.getPassword()), XaConstant.UserStatus.status_normal);        if(userDetails == null) {        throw new LoginLockException("賬號或者密碼錯(cuò)誤");         }        //數(shù)據(jù)庫用戶的密碼          String password = userDetails.getPassword();          //與authentication里面的credentials相比較          if(!password.equals(MD5Util.getMD5String((String)token.getCredentials()))) {              //throw new BadCredentialsException("Invalid username/password");            throw new LoginLockException("賬號或者密碼錯(cuò)誤");         }          //授權(quán)          return new UsernamePasswordAuthenticationToken(userDetails, password,userDetails.getAuthorities());  }@Overridepublic boolean supports(Class<?> authentication) {return UsernamePasswordAuthenticationToken.class.equals(authentication); }}

我標(biāo)紅色的部分就是關(guān)鍵,在MyAuthenticationProvider  中注入了 UserDetailsService 

,調(diào)用了loadUserByUsername(username)方法

package com.threeti.danfoss.base.security;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;import com.threeti.danfoss.base.constant.XaConstant;import com.threeti.danfoss.base.entity.XaCmsUser;import com.threeti.danfoss.base.exception.LoginLockException;import com.threeti.danfoss.base.repository.XaCmsUserRepository;import com.threeti.danfoss.base.util.DateProcessUtil;/** * 登錄權(quán)限驗(yàn)證service * @author zj * */@Service("MsUserDetailsService")public class XaUserDetailsService implements UserDetailsService {    protected static final String ROLE_PREFIX = "ROLE_";    protected static final GrantedAuthority DEFAULT_USER_ROLE = new SimpleGrantedAuthority(ROLE_PREFIX + "USER");@AutowiredXaCmsUserRepository xaCmsUserRepository;public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException {XaUserDetails msUserDetails = new XaUserDetails();try {XaCmsUser user;//List<XaCmsUser> userList = xaCmsUserRepository.findByUserName(new String(username.getBytes("ISO-8859-1"),"UTF-8"));

// 這里也是關(guān)鍵,注意,我這里是通過工號進(jìn)行查詢的List<XaCmsUser> userList = xaCmsUserRepository.findByNumber(new String(username.getBytes("ISO-8859-1"),"UTF-8"));if(userList.size() > 0 && userList.get(0).getStatus() == XaConstant.UserStatus.status_lock){throw new LoginLockException("您輸入的賬號已被鎖定");}/*if(userList.size() > 0 && userList.get(0).getIsAdmin() != 1){throw new LoginAdminException("您的賬號不是管理員");}*/if(userList.size() > 0 && userList.get(0) != null){user = userList.get(0);user.setLastLoginDate(DateProcessUtil.getToday(DateProcessUtil.YYYYMMDDHHMMSS));xaCmsUserRepository.save(user);msUserDetails.setUsername(user.getNumber());msUserDetails.setPassword(user.getPassword());List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();GrantedAuthority authority = new SimpleGrantedAuthority(user.getRole().getRoleName());authorities.add(authority);//設(shè)置用戶oauth通過token訪問的權(quán)限authorities.add(DEFAULT_USER_ROLE);authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + "UNITY"));authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + "MOBILE"));msUserDetails.setAuthorities(authorities);//msUserDetails.setToken(TokenCenter.issueToken(user.getUserId()));}} catch (Exception e) {e.printStackTrace();}return msUserDetails;}}


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 临沭县| 宣武区| 大同市| 库伦旗| 潞城市| 石首市| 云浮市| 平安县| 柳河县| 台湾省| 伽师县| 伊金霍洛旗| 建宁县| 文成县| 珠海市| 桂东县| 虎林市| 西吉县| 军事| 于都县| 吕梁市| 阿图什市| 永平县| 三亚市| 绵竹市| 内丘县| 宜章县| 湖北省| 德阳市| 芜湖县| 高安市| 公主岭市| 临泉县| 张家港市| 平塘县| 屯昌县| 勐海县| 大兴区| 江城| 嵩明县| 白朗县|