spring boot(五)spring security

Spring security正则表达式

1.认证Authentication,确认用户能够访问当前系统spring

重写protect void configure(AuthenticationManagerBuilder auth){sql

1. auth.inMemoryAuthentication()数据库

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

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

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

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

}ui

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

//自定义类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();

}

相关文章
相关标签/搜索