1. 程式人生 > >springBoot+springSecurity 動態管理Restful風格許可權(三)

springBoot+springSecurity 動態管理Restful風格許可權(三)

2 連結2:為一個REST服務使用Spring Security的基本和摘要認證

3 springboot+springsecurity 非同步日誌 驗證碼 記住我 (驗證xml方式和註解方式事務同時存在的情況)

原來預設返回html的類(如跳轉到拒絕訪問頁面),使用自定義的類後,不跳轉到html,而是返回給前端狀態碼。

3和4結合看,但是以3為準,因為3全而且是可執行的完整專案。看對springsecurity的配置在resultful和非resultful風格下有什麼區別。

4的部分程式碼拷貝了一份:

如重寫拒絕訪問後的邏輯,原來是跳轉到拒絕訪問頁面,現在是返回狀態碼。

public class GoAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException exception) throws IOException, ServletException {
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.getWriter().print("{\"code\":1,\"message\":\""+exception.getMessage()+"\"}");
        response.getWriter().flush();
    }
}
@Configuration
@Import(RootConfig.class)
public class GoWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    //......

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .exceptionHandling()
                    .accessDeniedHandler(new GoAccessDeniedHandler())
                    .authenticationEntryPoint(new GoAuthenticationEntryPoint())
                .and().authorizeRequests()
                    .antMatchers("/", "/csrf").permitAll()
                    .antMatchers("/hello").hasAuthority("ADMIN")
                    .anyRequest().authenticated()
                .and().formLogin()
                    .loginProcessingUrl("/login").permitAll()
                    .successHandler(new GoAuthenticationSuccessHandler())
                    .failureHandler(new GoAuthenticationFailureHandler())
                .and().logout()
                    .logoutUrl("/logout")
                    .logoutSuccessHandler(new GoLogoutSuccessHandler())
                    .invalidateHttpSession(true)
                    .deleteCookies("JSESSIONID")
                .and().requiresChannel()
                    .antMatchers("/pomer").requiresSecure()
                    .anyRequest().requiresInsecure()
                .and().rememberMe()
                    .tokenValiditySeconds(1800)
                    .key("token_key");
    }
}