spring security 基本使用

Spring Security 使用基本流程

引入security模块
implementation ‘org.springframework.boot:spring-boot-starter-security’

编写账户自定义验证过程类:
//验证规则类
@Component
public class gtpUserDetailsService implements UserDetailsService{

// 根据在/login里输入的username查出账户信息
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    System.out.println(">>>>>>>>>>>>>>>this is user details body...");
    Collection<GrantedAuthority> authorities = new ArrayList<>();

    String usernametmp=new String();
    if(username.equals("aa"))
        authorities.add(new SimpleGrantedAuthority("ROLE_manage"));

// securtiy的权限前缀ROLE_ 别忘了,在这里是必须要加的,不然会出现403错误。

    return new org.springframework.security.core.userdetails.User("aa", "698d51a19d8a121ce581499d7b701668", authorities);
}

}

编写配置类
//security配置类
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter{

@Autowired
private gtpUserDetailsService userDetailsServiceGTP;

// 配置各个资源访问权限,
//还可以自定义一些配置;比如登录页面,登录失败页面,启用rememberme…
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/auth/**").hasRole(“manage”);

    http.formLogin();
}

// 给工程配上自己制定的验证逻辑
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
System.out.println(“current this configure auto…”);

    //装配验证规则
    //添加密码编码解码类
    auth.userDetailsService(userDetailsServiceGTP).passwordEncoder(new PasswordEncoder() {

// 密码编码
@Override
public String encode(CharSequence rawPassword) {
MD5 md5=new MD5();
return md5.GetMD5(rawPassword.toString());
}

// 对照密码
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {

            MD5 md5=new MD5();
            String tpwd = this.encode(rawPassword);
            if(tpwd.equals(encodedPassword))
                return true;
            else
                return false;
        }
    });
}

}

启动类

@SpringBootApplication
public class SecurityexampleApplication {

public static void main(String[] args) {
	SpringApplication.run(SecurityexampleApplication.class, args);
}

}

项目源码和更详细信息:
https://gitee.com/whatitis/SpringSecurityExample

猜你喜欢

转载自blog.csdn.net/wangxudongx/article/details/87000153