Springsecurity

maven  导 security包

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

配置  注解

@Configuration
//@EnableWebSecurity   有配置时就不需要了
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    
  @Bean 密码
public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } @Autowired private DataSource datasource; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() // 表单登陆 .loginPage("/login") // 登陆页面 .defaultSuccessUrl("/index") .failureUrl("/login?error") .permitAll() // 放行 .and() .rememberMe() .tokenValiditySeconds(1209600) .key("mykey") .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/logout-success") .permitAll() .and().authorizeRequests() // 权限管理 .antMatchers("/login").permitAll() .antMatchers("/admin/**").hasRole("ROLE_ADMIN") .antMatchers("/user/**").hasRole("ROLE_USER") .anyRequest().authenticated(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userService); // 从内存中获取用户名 //.inMemoryAuthentication().withUser("mxz").password("mxz").roles("admin") //.and().and() // 从数据库中获取用户 角色 //.jdbcAuthentication().dataSource(datasource) // .usersByUsernameQuery("select user_name,password from users where user_name = ?"); }

实体类实现 userDetail

服务类 实现  UserDetailService

 记住登陆状态

.rememberMe().tokenValiditySeconds(1209600).tokenRepository(tokenRepository()).key("mykey")



@Bean
private PersistentTokenRepository tokenRepository() {
JdbcTokenRepositoryImpl jtr = new JdbcTokenRepositoryImpl();
jtr.setDataSource(dataSource);
return jtr;
}

JdbcTokenRepositoryImpl  中有贱表语句

  

public static final String CREATE_TABLE_SQL = "create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, "
+ "token varchar(64) not null, last_used timestamp not null)";

角色管理 

1.权限管理过滤器继承于AbstractSecurityInterceptor   实时监控用户的行为,防止用户访问被授权的资源。

2.权限配置资源 管理器   判断用户访问的资源是否在受保护的范围之内

3.权限决断器 实现了AccessDecisionManager 重载decide函数  在访问资源时,决断器判断用户拥有的角色是否对资源拥有访问权限。

 注册为bean

 

整体架构图

AuthenticationManager  就是拦截的校验管理器 

  内部含有一系列校验方式,手机登陆,账号密码登陆,又向登陆等

AuthenticationProvider   校验处理

UserDetailService  从数据库拿数据来校验

原文地址:https://www.cnblogs.com/mxz1994/p/8478971.html