SpringBoot整合Spring Security登錄表單詳細(xì)配置

部分引自 www.javaboy.org
formLogin這里還可以配置詳細(xì)一點(diǎn)

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("yzn").password("123").roles("admin")
                .and()
                .withUser("test").password("123").roles("user");
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasAnyRole("admin", "user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 登錄處理接口
                .loginProcessingUrl("/doLogin")
                // 定義登錄頁(yè)面,未登錄時(shí),訪問(wèn)一個(gè)需要登錄之后才能訪問(wèn)的接口,會(huì)自動(dòng)跳轉(zhuǎn)到該頁(yè)面
                .loginPage("/login")
                //定義登錄時(shí),用戶名的 key,默認(rèn)為 username
                .usernameParameter("uname")
                //定義登錄時(shí),用戶密碼的 key,默認(rèn)為 password
                .passwordParameter("passwd")
                //登錄成功的處理器
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        out.write("success");
                        out.flush();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        out.write("fail");
                        out.flush();
                    }
                })
                //和表單登錄相關(guān)的接口統(tǒng)統(tǒng)都直接通過(guò)
                .permitAll()
                .and()
                .csrf().disable();
    }
}
@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/admin/hello")
    public String admin() {
        return "hello admin";
    }

    @GetMapping("/user/hello")
    public String user() {
        return "hello user";
    }

    @GetMapping("/login")
    public String login() {
        return "please login!!!";
    }
}

利用postman測(cè)試

image.png

注銷表單配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("yzn").password("123").roles("admin")
                .and()
                .withUser("test").password("123").roles("user");
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasAnyRole("admin", "user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 登錄處理接口
                .loginProcessingUrl("/doLogin")
                // 定義登錄頁(yè)面,未登錄時(shí),訪問(wèn)一個(gè)需要登錄之后才能訪問(wèn)的接口,會(huì)自動(dòng)跳轉(zhuǎn)到該頁(yè)面
                .loginPage("/login")
                //定義登錄時(shí),用戶名的 key,默認(rèn)為 username
                .usernameParameter("uname")
                //定義登錄時(shí),用戶密碼的 key,默認(rèn)為 password
                .passwordParameter("passwd")
                //登錄成功的處理器
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        Map<String,Object> map = new HashMap();
                        map.put("status", 200);
                        // authentication.getPrincipal() 可以把登錄者信息取出來(lái)
                        map.put("msg", authentication.getPrincipal());
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        Map<String,Object> map = new HashMap();
                        map.put("status", 401);
                        map.put("msg", "failed");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                    }
                })
                //和表單登錄相關(guān)的接口統(tǒng)統(tǒng)都直接通過(guò)
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws IOException, ServletException {
                        res.setContentType("application/json;charset=utf-8");
                        PrintWriter out = res.getWriter();
                        Map<String,Object> map = new HashMap();
                        map.put("status", 200);
                        map.put("msg", "注銷登錄成功");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                    }
                })
                .and()
                .csrf().disable();
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容