SpringSecurity 使用過後的感受

SpringSecurity 一款權限框架,第一次配置真的是搞毛了。

首先導包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
 /*@Override
    public void configure(HttpSecurity http) throws Exception {
        // 請求進行攔截 驗證 accessToken
        http
                .authorizeRequests()
// .antMatchers("/api-user/web/**").hasAnyAuthority("SuperAdmin", "SysAdmin")
                ///任何請求,登錄後可以訪問
                .anyRequest()
                .authenticated()
                //允許所有用戶訪問與基於表單的登出
                .and()
                .logout()//設置登出
                .permitAll()
                //允許所有用戶訪問與基於表單的登錄
                .and()
                .formLogin()//設置表單登錄
                .usernameParameter("username").passwordParameter("password")//設置驗證的字段
                .loginPage("http://localhost:63343/tm_web/login.html")//設置登錄頁面
                .loginProcessingUrl("/api-user/public/storeUser/managerUserLogin")//設置請求登錄接口
                .successHandler(myAuthenctiationSuccessHandler) // 自定義登錄成功處理
                .failureHandler(myAuthenctiationFailureHandler) // 自定義登錄失敗處理
                //解決跨域
                .and()
                .cors()
                // 關閉csrf防護
                .and()
                .csrf()
                .disable();
    }*/
//登錄失敗
@Component("myAuthenctiationFailureHandler")
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        logger.info("登錄失敗");

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset=UTF-8");
       // response.getWriter().write(objectMapper.writeValueAsString(new BaseResponse(exception.getMessage())));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "200");
        jsonObject.put("message", "登錄失敗");
        jsonObject.put("objectMapper", objectMapper.writeValueAsString(new BaseResponse(exception.getMessage())));
        response.getWriter().write(jsonObject.toJSONString());
        ServletOutputStream out = response.getOutputStream();
        out.flush();
        out.close();
    }
}
//登陸成功
@Component("myAuthenctiationSuccessHandler")
public class MyAuthenctiationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {


    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        System.out.println("登錄成功");
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(userDetails);
        response.setContentType("application/json;charset=UTF-8");
        //  response.getWriter().write(objectMapper.writeValueAsString(authentication));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "200");
        jsonObject.put("message", "登錄成功");
        jsonObject.put("token", token);
        jsonObject.put("objectMapper", objectMapper.writeValueAsString(authentication));
        response.getWriter().write(jsonObject.toJSONString());
        ServletOutputStream out = response.getOutputStream();
        out.flush();
        out.close();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章