日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

spring security在分布式項(xiàng)目下的配置方法(案例詳解)

瀏覽:174日期:2023-08-09 15:08:31

分布式項(xiàng)目和傳統(tǒng)項(xiàng)目的區(qū)別就是,分布式項(xiàng)目有多個(gè)服務(wù),每一個(gè)服務(wù)僅僅只實(shí)現(xiàn)一套系統(tǒng)中一個(gè)或幾個(gè)功能,所有的服務(wù)組合在一起才能實(shí)現(xiàn)系統(tǒng)的完整功能。這會(huì)產(chǎn)生一個(gè)問(wèn)題,多個(gè)服務(wù)之間session不能共享,你在其中一個(gè)服務(wù)中登錄了,登錄信息保存在這個(gè)服務(wù)的session中,別的服務(wù)不知道啊,所以你訪(fǎng)問(wèn)別的服務(wù)還得在重新登錄一次,對(duì)用戶(hù)十分不友好。為了解決這個(gè)問(wèn)題,于是就產(chǎn)生了單點(diǎn)登錄:

**jwt單點(diǎn)登錄:**就是用戶(hù)在登錄服務(wù)登錄成功后,登錄服務(wù)會(huì)產(chǎn)生向前端響應(yīng)一個(gè)token(令牌),以后用戶(hù)再訪(fǎng)問(wèn)系統(tǒng)的資源的時(shí)候都要帶上這個(gè)令牌,各大服務(wù)對(duì)這個(gè)令牌進(jìn)行驗(yàn)證(令牌是否過(guò)期,令牌是否被篡改),驗(yàn)證通過(guò)了,可以訪(fǎng)問(wèn)資源,同時(shí),令牌中也會(huì)攜帶一些不重要的信息,比如用戶(hù)名,權(quán)限。通過(guò)解析令牌就能知道當(dāng)前登錄的用戶(hù)和用戶(hù)所擁有的權(quán)限。

下面我們就來(lái)寫(xiě)一個(gè)案例項(xiàng)目看看具體如何使用

1 創(chuàng)建項(xiàng)目結(jié)構(gòu)

1.1 父工程cloud-security

這是父工程所需要的包

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency></dependencies>

1.2 公共工程 security-common

這是公共工程所需要的包

<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId></dependency><dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version></dependency><!--jwt所需包--><dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version></dependency><dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope></dependency><dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred --> <version>0.11.2</version> <scope>runtime</scope></dependency>

1.3 認(rèn)證服務(wù)security-sever

這個(gè)服務(wù)僅僅只有兩項(xiàng)功能:

(1)用戶(hù)登錄,頒發(fā)令牌

(2)用戶(hù)注冊(cè)

我們這里只實(shí)現(xiàn)第一個(gè)功能

1.3.1 認(rèn)證服務(wù)所需的包

<dependency> <groupId>cn.lx.security</groupId> <artifactId>security-common</artifactId> <version>1.0-SNAPSHOT</version></dependency><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId></dependency><!--通用mapper--><dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.4</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>

1.3.2 配置application.yml

這里面的配置沒(méi)什么好說(shuō)的,都很簡(jiǎn)單

server: port: 8080spring: datasource: url: jdbc:mysql:///security_authority?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: driver-class-name: com.mysql.cj.jdbc.Driver thymeleaf: cache: false main: allow-bean-definition-overriding: truemybatis: type-aliases-package: cn.lx.security.doamin configuration: #駝峰 map-underscore-to-camel-case: truelogging: level: cn.lx.security: debug

1.3.3 導(dǎo)入domain,dao,service,config

這個(gè)可以在上篇文檔中找到,我們只需要service中的loadUserByUsername方法及其所調(diào)用dao中的方法

完整項(xiàng)目在我的github中,地址:git@github.com:lx972/cloud-security.git

配置文件我們也從上篇中復(fù)制過(guò)來(lái)MvcConfig,SecurityConfig

1.3.4 測(cè)試

訪(fǎng)問(wèn)http://localhost:8080/loginPage成功出現(xiàn)登錄頁(yè)面,說(shuō)明認(rèn)證服務(wù)的骨架搭建成功了

1.4 資源服務(wù)security-resource1

實(shí)際項(xiàng)目中會(huì)有很多資源服務(wù),我只演示一個(gè)

為了簡(jiǎn)單,資源服務(wù)不使用數(shù)據(jù)庫(kù)

1.4.1 資源服務(wù)所需的包

<dependency> <groupId>cn.lx.security</groupId> <artifactId>security-common</artifactId> <version>1.0-SNAPSHOT</version></dependency>

1.4.2 配置application.yml

server: port: 8090logging: level: cn.lx.security: debug

1.4.3 controller

擁有ORDER_LIST權(quán)限的才能訪(fǎng)問(wèn)

@RestController@RequestMapping('/order')public class OrderController { //@Secured('ORDER_LIST') @PreAuthorize(value = 'hasAuthority(’ORDER_LIST’)') @RequestMapping('/findAll') public String findAll(){ return 'order-list'; }}

擁有PRODUCT_LIST權(quán)限的才能訪(fǎng)問(wèn)

@RestController@RequestMapping('/product')public class ProductController { //@Secured('PRODUCT_LIST') @PreAuthorize(value = 'hasAuthority(’PRODUCT_LIST’)') @RequestMapping('/findAll') public String findAll(){ return 'product-list'; }}

1.4.4 security配置類(lèi)

@Configuration@EnableWebSecurity//這個(gè)注解先不要加//@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * Override this method to configure the {@link HttpSecurity}. Typically subclasses * should not invoke this method by calling super as it may override their * configuration. The default configuration is: * * <pre> * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic(); * </pre> * * @param http the {@link HttpSecurity} to modify * @throws Exception if an error occurs */ @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests().anyRequest().authenticated(); }}

1.4.5 測(cè)試

訪(fǎng)問(wèn)http://localhost:8090/order/findAll成功打印出order-list,服務(wù)搭建成功。

2 認(rèn)證服務(wù)實(shí)現(xiàn)登錄,頒發(fā)令牌

首先,我們必須知道我們的項(xiàng)目是前后端分離的項(xiàng)目,所以我們不能由后端控制頁(yè)面跳轉(zhuǎn)了,只能返回json串通知前端登錄成功,然后前端根據(jù)后端返回的信息控制頁(yè)面跳轉(zhuǎn)。

2.1 登錄成功或者登錄失敗后的源碼分析

UsernamePasswordAuthenticationFilter中登錄成功后走successfulAuthentication方法

/** * Default behaviour for successful authentication.認(rèn)證成功之后的默認(rèn)操作 * <ol> * <li>Sets the successful <tt>Authentication</tt> object on the * {@link SecurityContextHolder}</li> * <li>Informs the configured <tt>RememberMeServices</tt> of the successful login</li> * <li>Fires an {@link InteractiveAuthenticationSuccessEvent} via the configured * <tt>ApplicationEventPublisher</tt></li> * <li>Delegates additional behaviour to the {@link AuthenticationSuccessHandler}.</li> * </ol> * * Subclasses can override this method to continue the {@link FilterChain} after * successful authentication. * @param request * @param response * @param chain * @param authResult the object returned from the <tt>attemptAuthentication</tt> * method. * @throws IOException * @throws ServletException */protected void successfulAuthentication(HttpServletRequest request,HttpServletResponse response, FilterChain chain, Authentication authResult)throws IOException, ServletException {if (logger.isDebugEnabled()) {logger.debug('Authentication success. Updating SecurityContextHolder to contain: '+ authResult);} //將已通過(guò)認(rèn)證的Authentication保存到securityContext容器中,應(yīng)為后面的過(guò)濾器需要使用SecurityContextHolder.getContext().setAuthentication(authResult); //記住我rememberMeServices.loginSuccess(request, response, authResult);// Fire eventif (this.eventPublisher != null) {eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));} //這個(gè)方法你點(diǎn)進(jìn)去,就會(huì)發(fā)現(xiàn),真正作業(yè)面跳轉(zhuǎn)是在這里successHandler.onAuthenticationSuccess(request, response, authResult);}

UsernamePasswordAuthenticationFilter中登錄成功后走unsuccessfulAuthentication方法

/** * Default behaviour for unsuccessful authentication.認(rèn)證失敗之后的默認(rèn)操作 * <ol> * <li>Clears the {@link SecurityContextHolder}</li> * <li>Stores the exception in the session (if it exists or * <tt>allowSesssionCreation</tt> is set to <tt>true</tt>)</li> * <li>Informs the configured <tt>RememberMeServices</tt> of the failed login</li> * <li>Delegates additional behaviour to the {@link AuthenticationFailureHandler}.</li> * </ol> */protected void unsuccessfulAuthentication(HttpServletRequest request,HttpServletResponse response, AuthenticationException failed)throws IOException, ServletException {SecurityContextHolder.clearContext();if (logger.isDebugEnabled()) {logger.debug('Authentication request failed: ' + failed.toString(), failed);logger.debug('Updated SecurityContextHolder to contain null Authentication');logger.debug('Delegating to authentication failure handler ' + failureHandler);} //記住我失敗rememberMeServices.loginFail(request, response); //失敗后的頁(yè)面跳轉(zhuǎn)都在這里failureHandler.onAuthenticationFailure(request, response, failed);}

2.2 重寫(xiě)successfulAuthentication和unsuccessfulAuthentication方法

我們繼承UsernamePasswordAuthenticationFilter這個(gè)過(guò)濾器

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { /** * 這個(gè)方法必須有 * 在過(guò)濾器創(chuàng)建的時(shí)候手動(dòng)將AuthenticationManager對(duì)象給這個(gè)過(guò)濾器使用 * @param authenticationManager 這個(gè)對(duì)象在自己寫(xiě)的SecurityConfig里面 */ public AuthenticationFilter(AuthenticationManager authenticationManager) { super.setAuthenticationManager(authenticationManager); } /** * Default behaviour for successful authentication.認(rèn)證成功之后的默認(rèn)操作 * @param request * @param response * @param chain * @param authResult the object returned from the <tt>attemptAuthentication</tt> * method. * @throws IOException * @throws ServletException */ @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { //認(rèn)證成功的對(duì)象放入securityContext容器中 SecurityContextHolder.getContext().setAuthentication(authResult); // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( authResult, this.getClass())); } //創(chuàng)建令牌 Map<String, Object> claims=new HashMap<>(); SysUser sysUser = (SysUser) authResult.getPrincipal(); claims.put('username',sysUser.getUsername()); claims.put('authorities',authResult.getAuthorities()); //這個(gè)方法在下面介紹 String jwt = JwtUtil.createJwt(claims); //直接返回json ResponseUtil.responseJson(new Result('200', '登錄成功',jwt),response); } /** * Default behaviour for unsuccessful authentication. * @param request * @param response * @param failed */ @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { //清理容器中保存的認(rèn)證對(duì)象 SecurityContextHolder.clearContext(); //直接返回json ResponseUtil.responseJson(new Result('500', '登錄失敗'),response); }}

2.3 令牌創(chuàng)建

String jwt = JwtUtil.createJwt(claims);

這個(gè)方法干了什么事呢

/** * 創(chuàng)建令牌 * @param claims * @return */public static String createJwt(Map<String, Object> claims){ //獲取私鑰 String priKey = KeyUtil.readKey('privateKey.txt'); //將string類(lèi)型的私鑰轉(zhuǎn)換成PrivateKey,jwt只能接受PrivateKey的私鑰 PKCS8EncodedKeySpec priPKCS8 = null; try { priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(priKey)); KeyFactory keyf = KeyFactory.getInstance('RSA'); PrivateKey privateKey = keyf.generatePrivate(priPKCS8); //創(chuàng)建令牌 String jws = Jwts.builder() //設(shè)置令牌過(guò)期時(shí)間30分鐘 .setExpiration(new Date(System.currentTimeMillis()+1000*60*30)) //為令牌設(shè)置額外的信息,這里我們?cè)O(shè)置用戶(hù)名和權(quán)限,還可以根據(jù)需要繼續(xù)添加 .addClaims(claims) //指定加密類(lèi)型為rsa .signWith(privateKey, SignatureAlgorithm.RS256) //得到令牌 .compact(); log.info('創(chuàng)建令牌成功:'+jws); return jws; } catch (Exception e) { throw new RuntimeException('創(chuàng)建令牌失敗'); }}

獲取秘鑰的方法

public class KeyUtil { /** * 讀取秘鑰 * @param keyName * @return */ public static String readKey(String keyName){ //文件必須放在resources根目錄下 ClassPathResource resource=new ClassPathResource(keyName); String key =null; try { InputStream is = resource.getInputStream(); key = StreamUtils.copyToString(is, Charset.defaultCharset()); }catch (Exception e){ throw new RuntimeException('讀取秘鑰錯(cuò)誤'); } if (key==null){ throw new RuntimeException('秘鑰為空'); } return key; }}

2.4 響應(yīng)json格式數(shù)據(jù)給前端

封裝成了一個(gè)工具類(lèi)

public class ResponseUtil { /** * 將結(jié)果以json格式返回 * @param result 返回結(jié)果 * @param response * @throws IOException */ public static void responseJson(Result result, HttpServletResponse response) throws IOException { response.setContentType('application/json;charset=utf-8'); response.setStatus(200); PrintWriter writer = response.getWriter(); writer.write(JSON.toJSONString(result)); writer.flush(); writer.close(); }}

返回結(jié)果

@Data@AllArgsConstructor@NoArgsConstructorpublic class Result { private String code; private String msg; private Object data; public Result(String code, String msg) { this.code = code; this.msg = msg; }}3 認(rèn)證服務(wù)實(shí)現(xiàn)令牌驗(yàn)證和解析

除了security配置類(lèi)中配置的需要忽略的請(qǐng)求之外,其他所有請(qǐng)求必須驗(yàn)證請(qǐng)求頭中是否攜帶令牌,沒(méi)有令牌直接響應(yīng)json數(shù)據(jù),否則就驗(yàn)證和解析令牌。

security中有一個(gè)過(guò)濾器是實(shí)現(xiàn)令牌BasicAuthenticationFilter認(rèn)證的,只不過(guò)他是basic的,沒(méi)關(guān)系,我們繼承它,然后重寫(xiě)解析basic的方法

3.1 源碼分析

@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain chain) throws IOException, ServletException { final boolean debug = this.logger.isDebugEnabled(); //獲取請(qǐng)求頭中Authorization的值 String header = request.getHeader('Authorization'); if (header == null || !header.toLowerCase().startsWith('basic ')) { //值不符合條件直接放行 chain.doFilter(request, response); return; } try { //就是解析Authorization String[] tokens = extractAndDecodeHeader(header, request); assert tokens.length == 2; //tokens[0]用戶(hù)名 tokens[1]密碼 String username = tokens[0]; if (debug) { this.logger .debug('Basic Authentication Authorization header found for user ’' + username + '’'); } //判斷是否需要認(rèn)證(容器中有沒(méi)有該認(rèn)證對(duì)象) if (authenticationIsRequired(username)) { //創(chuàng)建一個(gè)對(duì)象 UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, tokens[1]); authRequest.setDetails( this.authenticationDetailsSource.buildDetails(request)); //進(jìn)行認(rèn)證,我們不關(guān)心它如何認(rèn)證,我們需要按自己的方法對(duì)令牌認(rèn)證解析 Authentication authResult = this.authenticationManager .authenticate(authRequest); if (debug) { this.logger.debug('Authentication success: ' + authResult); } //已認(rèn)證的對(duì)象保存到securityContext中 SecurityContextHolder.getContext().setAuthentication(authResult); //記住我 this.rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { this.logger.debug('Authentication request for failed: ' + failed); } this.rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (this.ignoreFailure) { chain.doFilter(request, response); } else { this.authenticationEntryPoint.commence(request, response, failed); } return; } chain.doFilter(request, response);}

3.2 重寫(xiě)doFilterInternal方法

繼承BasicAuthenticationFilter

public class TokenVerifyFilter extends BasicAuthenticationFilter { /** * Creates an instance which will authenticate against the supplied * {@code AuthenticationManager} and which will ignore failed authentication attempts, * allowing the request to proceed down the filter chain. * 在過(guò)濾器創(chuàng)建的時(shí)候手動(dòng)將AuthenticationManager對(duì)象給這個(gè)過(guò)濾器使用 * @param authenticationManager 這個(gè)對(duì)象在自己寫(xiě)的SecurityConfig里面 */ public TokenVerifyFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } /** * 過(guò)濾請(qǐng)求,判斷是否攜帶令牌 * @param request * @param response * @param chain * @throws IOException * @throws ServletException */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String header = request.getHeader('Authorization'); if (header == null || !header.toLowerCase().startsWith('bearer ')) { //直接返回json ResponseUtil.responseJson(new Result('403', '用戶(hù)未登錄'),response); return; } //得到j(luò)wt令牌 String jwt = StringUtils.replace(header, 'bearer ', ''); //解析令牌 String[] tokens = JwtUtil.extractAndDecodeJwt(jwt); //用戶(hù)名 String username = tokens[0]; //權(quán)限 List<SysPermission> authorities= JSON.parseArray(tokens[1], SysPermission.class); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( username, null, authorities ); //放入SecurityContext容器中 SecurityContextHolder.getContext().setAuthentication(authRequest); chain.doFilter(request, response); }}

3.3 驗(yàn)證解析令牌

/** * 解析令牌 * @param compactJws * @return */public static String decodeJwt(String compactJws){ //獲取公鑰 String pubKey = KeyUtil.readKey('publicKey.txt'); //將string類(lèi)型的私鑰轉(zhuǎn)換成PublicKey,jwt只能接受PublicKey的公鑰 KeyFactory keyFactory; try { X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec( new BASE64Decoder().decodeBuffer(pubKey)); keyFactory = KeyFactory.getInstance('RSA'); PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec); Claims body = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(compactJws).getBody(); String jwtString = JSON.toJSONString(body); //OK, we can trust this JWT log.info('解析令牌成功:'+jwtString); return jwtString; } catch (Exception e) { throw new RuntimeException('解析令牌失敗'); }}/** * 解析令牌并獲取用戶(hù)名和權(quán)限 * @param compactJws * @return String[0]用戶(hù)名 * String[1]權(quán)限 */public static String[] extractAndDecodeJwt(String compactJws){ //獲取令牌的內(nèi)容 String decodeJwt = decodeJwt(compactJws); JSONObject jsonObject = JSON.parseObject(decodeJwt); String username = jsonObject.getString('username'); String authorities = jsonObject.getString('authorities'); return new String[] { username, authorities };}

3.4 修改security配置類(lèi)

將自定義過(guò)濾器加入過(guò)濾器鏈

@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private IUserService iUserService; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; /** * 只有這個(gè)配置類(lèi)有AuthenticationManager對(duì)象,我們要把這個(gè)類(lèi)中的這個(gè)對(duì)象放入容器中 * 這樣在別的地方就可以自動(dòng)注入了 * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManager() throws Exception { AuthenticationManager authenticationManager = super.authenticationManagerBean(); return authenticationManager; } /** * Used by the default implementation of {@link #authenticationManager()} to attempt * to obtain an {@link AuthenticationManager}. If overridden, the * {@link AuthenticationManagerBuilder} should be used to specify the * {@link AuthenticationManager}. * * <p> * The {@link #authenticationManagerBean()} method can be used to expose the resulting * {@link AuthenticationManager} as a Bean. The {@link #userDetailsServiceBean()} can * be used to expose the last populated {@link UserDetailsService} that is created * with the {@link AuthenticationManagerBuilder} as a Bean. The * {@link UserDetailsService} will also automatically be populated on * {@link HttpSecurity#getSharedObject(Class)} for use with other * {@link SecurityContextConfigurer} (i.e. RememberMeConfigurer ) * </p> * * <p> * For example, the following configuration could be used to register in memory * authentication that exposes an in memory {@link UserDetailsService}: * </p> * * <pre> * &#064;Override * protected void configure(AuthenticationManagerBuilder auth) { * auth * // enable in memory based authentication with a user named * // &quot;user&quot; and &quot;admin&quot; * .inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;).and() * .withUser(&quot;admin&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;, &quot;ADMIN&quot;); * } * * // Expose the UserDetailsService as a Bean * &#064;Bean * &#064;Override * public UserDetailsService userDetailsServiceBean() throws Exception { * return super.userDetailsServiceBean(); * } * * </pre> * * @param auth the {@link AuthenticationManagerBuilder} to use * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //在內(nèi)存中注冊(cè)一個(gè)賬號(hào) //auth.inMemoryAuthentication().withUser('user').password('{noop}123').roles('USER'); //連接數(shù)據(jù)庫(kù),使用數(shù)據(jù)庫(kù)中的賬號(hào) auth.userDetailsService(iUserService).passwordEncoder(bCryptPasswordEncoder); } /** * Override this method to configure {@link WebSecurity}. For example, if you wish to * ignore certain requests. * * @param web */ @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers('/css/**', '/img/**', '/plugins/**', '/favicon.ico', '/loginPage'); } /** * Override this method to configure the {@link HttpSecurity}. Typically subclasses * should not invoke this method by calling super as it may override their * configuration. The default configuration is: * * <pre> * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic(); * </pre> * * @param http the {@link HttpSecurity} to modify * @throws Exception if an error occurs */ @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .httpBasic() .and() .authorizeRequests() .anyRequest().authenticated() .and() /** * 不要將自定義過(guò)濾器加component注解,而是在這里直接創(chuàng)建一個(gè)過(guò)濾器對(duì)象加入到過(guò)濾器鏈中,并傳入authenticationManager * 啟動(dòng)后,過(guò)濾器鏈中會(huì)同時(shí)出現(xiàn)自定義過(guò)濾器和他的父類(lèi),他會(huì)自動(dòng)覆蓋,并不會(huì)過(guò)濾兩次 * * 使用component注解會(huì)產(chǎn)生很多問(wèn)題: * 1. web.ignoring()會(huì)失效,上面的資源還是會(huì)經(jīng)過(guò)自定義的過(guò)濾器 * 2.過(guò)濾器鏈中出現(xiàn)的是他們父類(lèi)中的名字 * 3.登錄的時(shí)候(訪(fǎng)問(wèn)/login),一直使用匿名訪(fǎng)問(wèn),不會(huì)去數(shù)據(jù)庫(kù)中查詢(xún) */ .addFilterAt(new AuthenticationFilter(super.authenticationManager()), UsernamePasswordAuthenticationFilter.class) .addFilterAt(new TokenVerifyFilter(super.authenticationManager()), BasicAuthenticationFilter.class) //.formLogin().loginPage('/login.jsp').loginProcessingUrl('/login').defaultSuccessUrl('/index.jsp').failureForwardUrl('/failer.jsp').permitAll() .formLogin().loginPage('/loginPage').loginProcessingUrl('/login').permitAll() .and() .logout().logoutUrl('/logout').logoutSuccessUrl('/loginPage').invalidateHttpSession(true).permitAll(); }}4 資源服務(wù)實(shí)現(xiàn)令牌驗(yàn)證和解析

復(fù)制認(rèn)證服務(wù)的TokenVerifyFilter到資源服務(wù)

然后修改security的配置文件

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * Override this method to configure the {@link HttpSecurity}. Typically subclasses * should not invoke this method by calling super as it may override their * configuration. The default configuration is: * * <pre> * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic(); * </pre> * * @param http the {@link HttpSecurity} to modify * @throws Exception if an error occurs */ @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests().anyRequest().authenticated() .and() //禁用session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() //添加自定義過(guò)濾器 .addFilterAt(new TokenVerifyFilter(super.authenticationManager()), BasicAuthenticationFilter.class); }}

到此這篇關(guān)于spring security在分布式項(xiàng)目下的配置方法(案例詳解)的文章就介紹到這了,更多相關(guān)spring security分布式內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区
亚洲一卡久久| 亚洲一区资源| 99久久精品网| 91免费精品| av免费不卡国产观看| 亚洲激精日韩激精欧美精品| 日本麻豆一区二区三区视频| 亚洲在线成人| 成人片免费看| 97在线精品| 精品九九在线| 久久久久久久久丰满| 日韩一级网站| 综合国产精品| 国产精品va视频| 日韩一区二区三区在线免费观看| 国产精品久久久免费| 激情久久一区二区| 国产91久久精品一区二区| 亚洲一级淫片| 国产精品手机在线播放| 欧美丝袜一区| 国产欧美日韩影院| 国产精品一区三区在线观看| 一区二区精品| 国产欧美亚洲一区| 国产精品一在线观看| 日韩va欧美va亚洲va久久| 精品一区毛片| 亚洲欧洲av| 亚洲精品婷婷| 日韩激情网站| 日韩精品免费一区二区夜夜嗨| 国产视频一区免费看| 中文字幕免费一区二区| 不卡在线一区| 欧美日本不卡| 久久国产中文字幕| 亚洲91精品| 久久av免费| 久久久夜精品| 97人人精品| 国产国产精品| 蜜桃tv一区二区三区| 九九久久国产| 麻豆精品蜜桃视频网站| 亚洲在线久久| 国产欧美日韩精品高清二区综合区 | 国产成人免费av一区二区午夜| 国内一区二区三区| 五月激情久久| 国产亚洲在线观看| 久久蜜桃资源一区二区老牛| 精品91久久久久| 久久久久久自在自线| 免费看久久久| 亚洲成人三区| jiujiure精品视频播放| 午夜日韩在线| 国产精品调教视频| 亚洲精品国产精品粉嫩| 亚洲最大av| 合欧美一区二区三区| 98精品久久久久久久| 久久亚洲资源中文字| 91亚洲无吗| 国产情侣一区在线| 成人羞羞在线观看网站| 伊人久久亚洲热| 日本欧美韩国一区三区| 精品国产18久久久久久二百| 久久一区二区三区电影| 日本大胆欧美人术艺术动态| 国产日产精品_国产精品毛片 | 亚洲人妖在线| 欧美aⅴ一区二区三区视频| 日韩中文首页| 视频一区视频二区在线观看| 日韩精品一级| 亚洲综合电影| 亚洲制服一区| 精品九九在线| 久久亚洲风情| 久久精品国产亚洲一区二区三区| 久久久久免费av| 久久狠狠久久| 999久久久国产精品| 亚洲精品四区| 成人啊v在线| 老司机久久99久久精品播放免费| 久久99久久人婷婷精品综合| 日韩欧美不卡| 九色精品91| 亚洲特级毛片| 99热精品久久| 国产精品呻吟| 一区二区三区四区在线观看国产日韩| 亚洲影院天堂中文av色| 日韩视频不卡| 免费在线成人| 蜜桃tv一区二区三区| 欧美激情麻豆| 免费在线观看视频一区| 国产成人精品一区二区免费看京| 欧美精品激情| 国产aa精品| 日韩av资源网| 久久国产88| 国产不卡人人| 蘑菇福利视频一区播放| 精品三级av在线导航| 亚洲精品动态| av日韩中文| 麻豆成人91精品二区三区| 亚洲精品综合| 亚洲综合另类| 日韩免费一区| 国产在线日韩精品| 日韩精品a在线观看91| 国产综合激情| 国产精品theporn| 亚洲精品一二| 亚洲在线国产日韩欧美| 91精品蜜臀一区二区三区在线| 日本国产欧美| 久久国产精品99国产| 午夜精品久久久久久久久久蜜桃| 国产精品多人| 日韩av资源网| av综合电影网站| 国产情侣久久| 国产精品亚洲片在线播放| 久久三级福利| 久久国际精品| 日韩一级网站| 亚洲精品婷婷| 免费在线观看日韩欧美| 黄色免费成人| 久久高清国产| 欧美+亚洲+精品+三区| 国产精品羞羞答答在线观看| 亚洲乱亚洲高清| 中文字幕日本一区二区| 国产亚洲欧美日韩在线观看一区二区| 亚洲v天堂v手机在线| 亚洲精品动态| 日韩激情网站| 久久99久久人婷婷精品综合| 国产亚洲高清在线观看| 国产精品久久| 日韩88av| 亚洲精品a级片| 四虎精品一区二区免费| 首页国产欧美久久| 婷婷精品在线观看| 久久国际精品| 精品精品99| 青青国产91久久久久久| 97精品国产福利一区二区三区| 福利一区和二区| 精品国产亚洲一区二区三区| 国产伦精品一区二区三区千人斩| 久久久久久久久99精品大| 日韩在线观看| 久久久777| 日韩深夜视频| 国精品一区二区| 午夜一级在线看亚洲| 日本一区二区高清不卡| 日韩成人综合| 98精品久久久久久久| 水蜜桃精品av一区二区| 久久电影tv| 国产在线不卡| 国产亚洲精品久久久久婷婷瑜伽| 亚洲激情精品| 日本一区中文字幕| 国产人成精品一区二区三| 久久永久免费| 日韩不卡在线| 日韩视频一区| 日韩欧美精品一区二区综合视频| 日韩欧美三区| 国产精品hd| 91精品一区国产高清在线gif| 日韩网站中文字幕| 妖精视频成人观看www| 亚洲精品第一| 麻豆视频观看网址久久| 亚洲91视频| 亚洲精选av| 国产精品欧美三级在线观看 | 日韩欧美四区| 国产精品欧美在线观看| 超级白嫩亚洲国产第一| 久久久久久久久99精品大| 亚洲欧美日韩国产一区二区| 91在线成人| 91精品韩国| 国产精品99久久免费|