springboot笔记(10)spring-security安全管理-01

1.创建springboot项目

在这里插入图片描述
在这里插入图片描述

2.通过application配置文件设置账号,密码,权限

注意
什么都不设置的话
项目默认账号:user
默认密码:控制台打印的

spring.security.user.name=chenyp
spring.security.user.password=123
spring.security.user.roles=admin

3.通过配置类设置账号,密码,权限

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //不加密
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("chenyp").password("123").roles("admin")
                .and()
                .withUser("小雨伞").password("123").roles("user");
    }
}

3.在配置类中设置权限,登录接口

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        		//设置权限
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasAnyRole("user","admin")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/doLogin")
                .loginPage("/login")
                .usernameParameter("uname")
                .passwordParameter("passwd")
                //登录成功
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(
                            HttpServletRequest req, HttpServletResponse resp,
                            Authentication authentication)
                            throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out=resp.getWriter();
                        Map<String,Object> map=new HashMap<>();
                        map.put("status",200);
                        map.put("msg",authentication.getPrincipal());
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                //登录失败
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(
                            HttpServletRequest req, HttpServletResponse resp,
                            AuthenticationException e)
                            throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out=resp.getWriter();
                        Map<String,Object> map=new HashMap<>();
                        map.put("status",401);
                        if (e instanceof LockedException){
                            map.put("msg","账户被锁定,登录失败!");
                        }else if (e instanceof BadCredentialsException){
                            map.put("msg","用户名和密码输入错误,登录失败!");
                        }else {
                            map.put("msg","登录失败!");
                        }
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                //账号登出
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(
                            HttpServletRequest req, HttpServletResponse resp,
                            Authentication authentication)
                            throws IOException, ServletException {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out=resp.getWriter();
                        Map<String,Object> map=new HashMap<>();
                        map.put("status",200);
                        map.put("msg","注销登录成功");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .and()
                .csrf().disable();
    }

4.配置多个httpsecurity

@Configuration
public class MultiHttpSecurityConfig {

    //不加密
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }


    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("chenyp").password("111").roles("admin")
                .and()
                .withUser("陈耀鹏").password("222").roles("user");
    }

    @Configuration
    @Order(1)
    public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/admin/**").authorizeRequests().anyRequest().hasAnyRole("admin");
        }
    }

    @Configuration
    public static class OtherSecurityConfig extends WebSecurityConfigurerAdapter{
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginProcessingUrl("/doLogin")
                    .permitAll()
                    .and()
                    .csrf().disable();
        }
    }
}
发布了33 篇原创文章 · 获赞 19 · 访问量 3506

猜你喜欢

转载自blog.csdn.net/qq_42794826/article/details/103948803
今日推荐