详解spring security 配置多个AuthenticationProvider

 更新时间:2017年05月11日 09:56:13   作者:暮夜望日  
这篇文章主要介绍了详解spring security 配置多个AuthenticationProvider ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

前言

发现很少关于spring security的文章,基本都是入门级的,配个UserServiceDetails或者配个路由控制就完事了,而且很多还是xml配置,国内通病...so,本文里的配置都是java配置,不涉及xml配置,事实上我也不会xml配置

spring security的大体介绍

spring security本身如果只是说配置,还是很简单易懂的(我也不知道网上说spring security难,难在哪里),简单不需要特别的功能,一个WebSecurityConfigurerAdapter的实现,然后实现UserServiceDetails就是简单的数据库验证了,这个我就不说了。

spring security大体上是由一堆Filter(所以才能在spring mvc前拦截请求)实现的,Filter有几个,登出Filter(LogoutFilter),用户名密码验证Filter(UsernamePasswordAuthenticationFilter)之类的,Filter再交由其他组件完成细分的功能,例如最常用的UsernamePasswordAuthenticationFilter会持有一个AuthenticationManager引用,AuthenticationManager顾名思义,验证管理器,负责验证的,但AuthenticationManager本身并不做具体的验证工作,AuthenticationManager持有一个AuthenticationProvider集合,AuthenticationProvider才是做验证工作的组件,AuthenticationManager和AuthenticationProvider的工作机制可以大概看一下这两个的java doc,然后成功失败都有相对应该Handler 。大体的spring security的验证工作流程就是这样了。

开始配置多AuthenticationProvider

首先,写一个内存认证的AuthenticationProvider,这里我简单地写一个只有root帐号的AuthenticationProvider

package com.scau.equipment.config.common.security.provider;

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.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017-05-10.
 */
@Component
public class InMemoryAuthenticationProvider implements AuthenticationProvider {
  private final String adminName = "root";
  private final String adminPassword = "root";

  //根用户拥有全部的权限
  private final List<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("CAN_SEARCH"),
      new SimpleGrantedAuthority("CAN_SEARCH"),
      new SimpleGrantedAuthority("CAN_EXPORT"),
      new SimpleGrantedAuthority("CAN_IMPORT"),
      new SimpleGrantedAuthority("CAN_BORROW"),
      new SimpleGrantedAuthority("CAN_RETURN"),
      new SimpleGrantedAuthority("CAN_REPAIR"),
      new SimpleGrantedAuthority("CAN_DISCARD"),
      new SimpleGrantedAuthority("CAN_EMPOWERMENT"),
      new SimpleGrantedAuthority("CAN_BREED"));

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if(isMatch(authentication)){
      User user = new User(authentication.getName(),authentication.getCredentials().toString(),authorities);
      return new UsernamePasswordAuthenticationToken(user,authentication.getCredentials(),authorities);
    }
    return null;
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return true;
  }

  private boolean isMatch(Authentication authentication){
    if(authentication.getName().equals(adminName)&&authentication.getCredentials().equals(adminPassword))
      return true;
    else
      return false;
  }
}

support方法检查authentication的类型是不是这个AuthenticationProvider支持的,这里我简单地返回true,就是所有都支持,这里所说的authentication为什么会有多个类型,是因为多个AuthenticationProvider可以返回不同的Authentication。

public Authentication authenticate(Authentication authentication) throws AuthenticationException 方法就是验证过程。

如果AuthenticationProvider返回了null,AuthenticationManager会交给下一个支持authentication类型的AuthenticationProvider处理。

 另外需要一个数据库认证的AuthenticationProvider,我们可以直接用spring security提供的DaoAuthenticationProvider,设置一下UserServiceDetails和PasswordEncoder就可以了

 @Bean
  DaoAuthenticationProvider daoAuthenticationProvider(){
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
    daoAuthenticationProvider.setUserDetailsService(userServiceDetails);
    return daoAuthenticationProvider;
  }

最后在WebSecurityConfigurerAdapter里配置一个含有以上两个AuthenticationProvider的AuthenticationManager,依然重用spring security提供的ProviderManager

package com.scau.equipment.config.common.security;

import com.scau.equipment.config.common.security.handler.AjaxLoginFailureHandler;
import com.scau.equipment.config.common.security.handler.AjaxLoginSuccessHandler;
import com.scau.equipment.config.common.security.provider.InMemoryAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/2/17.
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  UserDetailsService userServiceDetails;

  @Autowired
  InMemoryAuthenticationProvider inMemoryAuthenticationProvider;

  @Bean
  DaoAuthenticationProvider daoAuthenticationProvider(){
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
    daoAuthenticationProvider.setUserDetailsService(userServiceDetails);
    return daoAuthenticationProvider;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .rememberMe().alwaysRemember(true).tokenValiditySeconds(86400).and()
        .authorizeRequests()
          .antMatchers("/","/*swagger*/**", "/v2/api-docs").permitAll()
          .anyRequest().authenticated().and()
        .formLogin()
          .loginPage("/")
          .loginProcessingUrl("/login")
          .successHandler(new AjaxLoginSuccessHandler())
          .failureHandler(new AjaxLoginFailureHandler()).and()
        .logout().logoutUrl("/logout").logoutSuccessUrl("/");
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/public/**", "/webjars/**", "/v2/**", "/swagger**");
  }

  @Override
  protected AuthenticationManager authenticationManager() throws Exception {
    ProviderManager authenticationManager = new ProviderManager(Arrays.asList(inMemoryAuthenticationProvider,daoAuthenticationProvider()));
    //不擦除认证密码,擦除会导致TokenBasedRememberMeServices因为找不到Credentials再调用UserDetailsService而抛出UsernameNotFoundException
    authenticationManager.setEraseCredentialsAfterAuthentication(false);
    return authenticationManager;
  }

  /**
   * 这里需要提供UserDetailsService的原因是RememberMeServices需要用到
   * @return
   */
  @Override
  protected UserDetailsService userDetailsService() {
    return userServiceDetails;
  }
}

基本上都是重用了原有的类,很多都是默认使用的,只不过为了修改下行为而重新配置。其实如果偷懒,直接用一个UserDetailsService,在里面做各种认证也是可以的~不过这样就没意思了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java StringBuilder类相关知识总结

    Java StringBuilder类相关知识总结

    这篇文章主要介绍了Java StringBuilder类相关知识总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • JAVA面试题之缓存击穿、缓存穿透、缓存雪崩的三者区别

    JAVA面试题之缓存击穿、缓存穿透、缓存雪崩的三者区别

    当服务器QPS比较高,并且对数据的实时性要求不高时,往往会接入缓存以达到快速Response、降低数据库压力的作用,常用来做缓存的中间件如Redis等。本文主要介绍了JAVA面试时常考的缓存击穿、穿透、雪崩场景三者区别,有兴趣的小伙伴可以看一下
    2021-11-11
  • 深入理解Java8新特性之接口中的默认方法和静态方法

    深入理解Java8新特性之接口中的默认方法和静态方法

    从Java8开始,程序允许在接口中包含带有具体实现的方法,使用default修饰,这类方法就是默认方法。默认方法在接口中可以添加多个,并且Java8提供了很多对应的接口默认方法,接下来让我们一起来看看吧
    2021-11-11
  • java 根据前端返回的字段名进行查询数据

    java 根据前端返回的字段名进行查询数据

    本文介绍了如何在Java中使用SpringDataJPA实现动态查询功能,以便根据前端传递的字段名动态构建查询语句,通过创建实体类、Repository接口、构建动态查询、在Service层和Controller中使用动态查询,实现了前后端分离架构中的灵活查询需求
    2024-11-11
  • 工厂方法在Spring框架中的运用

    工厂方法在Spring框架中的运用

    这篇文章介绍了工厂方法在Spring框架中的运用,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • MyBatis中$和#的深入讲解

    MyBatis中$和#的深入讲解

    这篇文章主要给大家介绍了关于MyBatis中$和#的相关资料,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • java中多线程与线程池的基本使用方法

    java中多线程与线程池的基本使用方法

    在Java中,我们可以利用多线程来最大化地压榨CPU多核计算的能力,下面这篇文章主要给大家介绍了关于java中多线程与线程池基本使用的相关资料,需要的朋友可以参考下
    2021-09-09
  • 使用maven的profile构建不同环境配置的方法

    使用maven的profile构建不同环境配置的方法

    这篇文章主要介绍了使用maven的profile构建不同环境配置的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Java学习之如何进行JSON解析

    Java学习之如何进行JSON解析

    JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它算是JavaScript语言的一部分,与XML一样都可以用于数据的存储和传输,本文讲给大家介绍如何进行JSON解析,需要的朋友可以参考下
    2023-12-12
  • Java ObjectMapper的使用和使用过程中遇到的问题

    Java ObjectMapper的使用和使用过程中遇到的问题

    在Java开发中,ObjectMapper是Jackson库的核心类,用于将Java对象序列化为JSON字符串,或者将JSON字符串反序列化为Java对象,这篇文章主要介绍了Java ObjectMapper的使用和使用过程中遇到的问题,需要的朋友可以参考下
    2024-07-07

最新评论