springboot notes (10) spring security security management-01

1. Create a springboot project


2. Set the account, password and authority through the application configuration file

Be careful
If you don't set anything up
Project default account: user
Default password: console printed

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

3. Set account, password and authority through configuration class

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //No encryption
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }


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

3. Set permissions and login interface in configuration class

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        		//Setting permissions
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasAnyRole("user","admin")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/doLogin")
                .loginPage("/login")
                .usernameParameter("uname")
                .passwordParameter("passwd")
                //Login successfully
                .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();
                    }
                })
                //Login failed
                .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","Account locked,Login failed!");
                        }else if (e instanceof BadCredentialsException){
                            map.put("msg","Wrong user name and password,Login failed!");
                        }else {
                            map.put("msg","Login failed!");
                        }
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                //Account number logout
                .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","Log out successfully");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .and()
                .csrf().disable();
    }

4. Configure multiple httpsecurity

@Configuration
public class MultiHttpSecurityConfig {

    //No encryption
    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }


    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("chenyp").password("111").roles("admin")
                .and()
                .withUser("Chen Yao Peng").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 original articles published, 19 praised, 3500 visited
Private letter follow

Tags: JSON Spring SpringBoot

Posted on Sun, 12 Jan 2020 11:36:42 -0500 by vasilis