spring boot(五)spring security

Spring security

1.认证Authentication,确认用户可以访问当前系统

重写protect void configure(AuthenticationManagerBuilder auth){

1. auth.inMemoryAuthentication()

.withUser(“ss”).password(“ss”).roles(“ROLE_ADMIN”);//内存中的用户

2. auth.jdbcAuthentication().dataSource(dataSource) //jdbc中的用户

(Spring security中默认了数据库的结构,可以自定义查询用户和权限的sql语句)

3. auth.userDetaisService(customUserService) //通用的用户,见下:

}

通用的用户:数据访问不仅仅是内存或jdbc,还可能是非关系型数据库,或JPA,需要自定义实现UserDetailService接口

//自定义类CustomUserService实现UserDetailsService接口

public class CustomUserService implements UserDetailsService{

    @Autowired

    SysUserRepository userRepository;


    @Override

    public UserDetails loadUserByUsername(String name){

        //SysUser是系统的用户领域类对象

        SysUser user = userRepository.findbyUsername(name);

        List<GrantedAuthority> authoritys = new ArrayList<GrantedAuthority>();

        authoritys.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        //User来自于spring security框架

        return new User(user.getUsername(),user.getPassword(),authoritys);

    }

}


//注册这个实现类

@Bean

UserDetaisService customUserService(){

    return new CustomUserService();

}

2.授权Authorization,确认用户在当前系统下所拥有的功能权限

重写protected void configure(HttpSecurity http)

请求拦截路径匹配器:

autMatchers:使用ant风格的路径匹配

regexMatchers:正则表达式匹配路径

anyRequest:匹配所有的请求路径

匹配请求路径后,进行安全处理,Spring security提供了安全处理方法:

access(String)spring el表达式为true时可访问;

denyAll()用户不能访问;

permitAll()用户可以任意访问

authenticated()用户登录后可以访问

… … 

如:@Override

protected void configure(HttpSecurity http){

    http.authorizeRequests() //开始请求权限配置


            .autMatchers("/admin/**").hasRole("ROLE_ADMIN")

            .autMatchers("/user/**").hasAnyRole("ROLE_ADMIN","ROLE_USER")

            .anyRequest().authenticted();//其余所有用户都需要认证后(登陆后)才可以访问

}

定制登录行为:

@Override

protected void configure(HttpSecurity http){

    http.fromLogin()    //定制登录操作

            .loginPage("/login")    

            .defaultSuccessUrl("/index")

            .failureUrl("/login?error")

            .permitAll()    

            .and()

            .rememberMe()   //开启cookie存储用户信息

                .tokenValiditySeconds(1209600)

                .key("myKey")

            .and()

            .logout()

                .logoutUrl("/custome-logout")

                .logoutSuccessUrl("/logout-success")

                .permitAll();

}

猜你喜欢

转载自blog.51cto.com/13580976/2135270