用springSecurity实现用户登录功能

  • Post author:
  • Post category:其他


1.导入springSecurity的坐标

<!--spring security 组件-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.创建springSecurity的配置类springConfig.java,并继承WebSecurityConfigurerAdapter类。①重写放行静态资源的configure(WebSecurity web)并配置要放行的静态资源,②再重写configure(HttpSecurity http)配置登录的地址、登录成功后的地址、登录成功与失败的逻辑处理类以及配置对登录所需的资源进行放行而对其他任何资源进行登录认证③添加登录的逻辑处理和登录验证、密码加密的方法④重写configure(AuthenticationManagerBuilder auth)方法让springSecurity框架调用登录认证处理和密码加密处理的方法。实现登录校验.

@SpringBootConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

   //注入登录成功的处理对象,该类代码文章最后面
   @Autowired
    private JxcAuthenticationSuccessHandler jxcAuthenticationSuccessHandler;


    @Autowired
    private JxcAuthenticationFailedHandler jxcAuthenticationFailedHandler;

     /**
     * 重写放行静态资源的configure(WebSecurity web)方法
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/images/**",
                "/css/**",
                "/js/**",
                "/lib/**",
                "/error/**");
    }
     /**
     * 配置登录地址,登录成功后的地址
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //禁用csrf
        http.csrf().disable()
            .addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class)
            // 允许iframe 页面嵌套
            .headers().frameOptions().disable()
            .and()
                .formLogin()//允许表单登录
                .usernameParameter("userName")//登录时的用户参数
                .passwordParameter("password")
                .loginPage("/index")//登录界面
                .loginProcessingUrl("/login") //这是框架提供的登录时访问的地址
                .successHandler(jxcAuthenticationSuccessHandler)//指定登录成功的处理逻辑类
                .failureHandler(jxcAuthenticationFailedHandler)//指定登录失败的处理逻辑类
         
            .and()
                //放行下面的三个登录要用到的请求
                .authorizeRequests().antMatchers("/index","/login","/image").permitAll()
                //对于任何其他请求都进行拦截认证 
                .anyRequest().authenticated();
    }

     /**
     * 用springSecurity提供的登录逻辑处理接口类实现登录逻辑的处理。
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService(){
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws   UsernameNotFoundException {
                User userDetails = userService.findUserByUserName(username);
                return userDetails;//框架会根据返回的userDetails处理登录的验证
            }
        };
    }

     /**
     * 对密码进行加密的实现方法
     * @return
     */
    @Bean
    public PasswordEncoder encoder(){
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 让框架来调用userDetailsService的实现和密码加密解密的实现
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(encoder());
    }

}

3.再前端如何获取登录成功的用户信息?

${(Session.SPRING_SECURITY_CONTEXT.authentication.principal.username)!”zeng”}

!”zeng”指如果获取的username为空就设置一个默认值”zeng”



版权声明:本文为qq_45880237原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。