Spring Security动态认证用户信息

新建CustomUserDetailsService类

package com.mengxuegu.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("请求认证的用户名:"+username);
        //1.通过请求的用户名去数据库中查询用户信息
        if(!"meng".equalsIgnoreCase(username)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        String password = passwordEncoder.encode("1234");

        //2.查询该用户有哪些权限

        //3.封装用户信息和权限信息
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN"));
    }
}

配置SpringSecurityConfig

package com.mengxuegu.security.config;

import com.mengxuegu.security.properties.AuthenticationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


/**
 * alt+/ 导包
 * ctrl+o 覆盖
 * @Auther: 梦学谷 www.mengxuegu.com
 */
@EnableWebSecurity // 开启springsecurity过滤链 filter
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AuthenticationProperties authenticationProperties;

    @Bean
    public PasswordEncoder passwordEncoder(){
        // 明文+随机盐值-》加密存储
        return new BCryptPasswordEncoder();
    }

    @Autowired
    UserDetailsService customUserDetailsService;

    /**
     * 认证管理器:
     * 1. 认证信息(用户名,密码)
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        String password = passwordEncoder().encode("123456");
//        logger.info("加密之后存储的密码:"+password);
//        auth.inMemoryAuthentication().withUser("root").password(password).authorities("ADMIN");
        auth.userDetailsService(customUserDetailsService);
    }

    /**
     * 资源权限配置:
     * 1. 被拦截的资源
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("用户认证");
//       http.httpBasic() // 采用 httpBasic认证方式
        http.formLogin() // 表单登录方式
                .loginPage(authenticationProperties.getLoginPage())   //配置登录页面
                .loginProcessingUrl(authenticationProperties.getLoginProcessingUrl())  //登录表单提交处理url,默认是/login
                .usernameParameter(authenticationProperties.getUsernameParameter())
                .passwordParameter(authenticationProperties.getPasswordParameter())
            .and()
            .authorizeRequests() // 认证请求
            .antMatchers(authenticationProperties.getLoginPage()).permitAll()
            .anyRequest().authenticated() //所有访问该应用的http请求都要通过身份认证才可以访问
        ; // 注意不要少了分号
    }

    /**
     * 一般针对静态资源放行
     * @param web
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers(authenticationProperties.getStaticPaths());
    }
}
posted @ 2020-11-05 21:37  xl4ng  阅读(161)  评论(0编辑  收藏  举报