spring security相关配置——用户、密码、权限

在上篇文章中介绍了如何自定义登录页面并实现了登录,但是使用的用户名和密码都是spring security默认的,即用户名是user,密码是每次启动时随机生成的一串密码。下面介绍几种设置用户名和密码的方法。

1.使用application.yml配置

spring security相关配置——用户、密码、权限_第1张图片

像上面这样配置完就可以实现自定义的用户名、密码和角色

2.基于内存的设置

spring security相关配置——用户、密码、权限_第2张图片

重写configure(AuthenticationManagerBuilder auth)方法然后使用inMemoryAuthentication()就可以设置用户名和密码了,上面的这些设置都只是分配了角色,但并没有对角色进行限制,接下来我们配置权限限制。

角色管理需要重写WebSecurityConfigureAdapter的另外一个方法——configure(HttpSecurity http),就是之前设置自定义登录页面的那个方法。直接帖代码:

protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/user/register/**").permitAll()    //不验证此路径
                .antMatchers("/admin/**")                        //让/admin?**下的内容只能让admin访问
                .hasRole("ADMIN")
                .antMatchers("/user/**")                        //让/user/**下的内容可以让admin和user俩个角色访问
                .access("hasAnyRole('ADMIN','USER')")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/user/login").loginProcessingUrl("/login").permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")                          //注销登录状态
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {}
                }).logoutSuccessHandler(new LogoutSuccessHandler() {
            @Override
            public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {    //注销成功后返回登录页面
                response.sendRedirect("/user/login");
            }
        })
                .permitAll()
                .and()
                .csrf().disable();
    }

我这里写的比较多,因为设置了其他的一些东西,但总的来说就是通过antMatchers方法设置权限,这样在controller分别设置/admin/**里的内容和/user/**作为测试,发现使用admin可以访问俩个controller下的接口,但是user角色只能访问user/**下面的接口,访问admin会返回403错误,403错误码就是表示没有权限访问资源。

配置中还有个logout方法,这个方法是用来注销登录状态的,可以设置注销成功后的操作,这里我设置为了注销成功后返回登录页面。下篇文章我完整的实现一个基于spring security + mybatis的注册登录功能,并且使用了官方推荐的BCryptPasswordEncoder加密方法。

 

你可能感兴趣的:(spring security相关配置——用户、密码、权限)