這篇文章主要介紹了Java SpringSecurity+JWT如何實現登錄認證的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Java SpringSecurity+JWT如何實現登錄認證文章都會有所收獲,下面我們一起來看看吧。
這里我們以
mall-portal
改造為例來說說如何實現。
第一步,給需要登錄認證的模塊添加mall-security
依賴:
<dependency> <groupId>com.macro.mall</groupId> <artifactId>mall-security</artifactId> </dependency>
第二步,添加MallSecurityConfig配置類,繼承mall-security
中的SecurityConfig配置,并且配置一個UserDetailsService接口的實現類,用于獲取登錄用戶詳情:
/** * mall-security模塊相關配置 * Created by macro on 2019/11/5. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true) publicclass MallSecurityConfig extends SecurityConfig { @Autowired private UmsMemberService memberService; @Bean public UserDetailsService userDetailsService() { //獲取登錄用戶信息 return username -> memberService.loadUserByUsername(username); } }
第三步,在application.yml中配置下不需要安全保護的資源路徑:
secure: ignored: urls:#安全路徑白名單 -/swagger-ui.html -/swagger-resources/** -/swagger/** -/**/v2/api-docs -/**/*.js -/**/*.css -/**/*.png -/**/*.ico -/webjars/springfox-swagger-ui/** -/druid/** -/actuator/** -/sso/** -/home/**
第四步,在UmsMemberController中實現登錄和刷新token的接口:
/** * 會員登錄注冊管理Controller * Created by macro on 2018/8/3. */ @Controller @Api(tags = "UmsMemberController", description = "會員登錄注冊管理") @RequestMapping("/sso") publicclass UmsMemberController { @Value("${jwt.tokenHeader}") private String tokenHeader; @Value("${jwt.tokenHead}") private String tokenHead; @Autowired private UmsMemberService memberService; @ApiOperation("會員登錄") @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public CommonResult login(@RequestParam String username, @RequestParam String password) { String token = memberService.login(username, password); if (token == null) { return CommonResult.validateFailed("用戶名或密碼錯誤"); } Map<String, String> tokenMap = new HashMap<>(); tokenMap.put("token", token); tokenMap.put("tokenHead", tokenHead); return CommonResult.success(tokenMap); } @ApiOperation(value = "刷新token") @RequestMapping(value = "/refreshToken", method = RequestMethod.GET) @ResponseBody public CommonResult refreshToken(HttpServletRequest request) { String token = request.getHeader(tokenHeader); String refreshToken = memberService.refreshToken(token); if (refreshToken == null) { return CommonResult.failed("token已經過期!"); } Map<String, String> tokenMap = new HashMap<>(); tokenMap.put("token", refreshToken); tokenMap.put("tokenHead", tokenHead); return CommonResult.success(tokenMap); } }
將SpringSecurity+JWT的代碼封裝成通用模塊后,就可以方便其他需要登錄認證的模塊來使用,下面我們來看看它是如何實現的,首先我們看下
mall-security
的目錄結構。
mall-security ├── component | ├── JwtAuthenticationTokenFilter -- JWT登錄授權過濾器 | ├── RestAuthenticationEntryPoint -- 自定義返回結果:未登錄或登錄過期 | └── RestfulAccessDeniedHandler -- 自定義返回結果:沒有權限訪問時 ├── config | ├── IgnoreUrlsConfig -- 用于配置不需要安全保護的資源路徑 | └── SecurityConfig -- SpringSecurity通用配置 └── util └── JwtTokenUtil -- JWT的token處理工具類
其實我也就添加了兩個類,一個IgnoreUrlsConfig,用于從application.yml中獲取不需要安全保護的資源路徑。一個SecurityConfig提取了一些SpringSecurity的通用配置。
IgnoreUrlsConfig中的代碼:
/** * 用于配置不需要保護的資源路徑 * Created by macro on 2018/11/5. */ @Getter @Setter @ConfigurationProperties(prefix = "secure.ignored") publicclass IgnoreUrlsConfig { private List<String> urls = new ArrayList<>(); }
SecurityConfig中的代碼:
/** * 對SpringSecurity的配置的擴展,支持自定義白名單資源路徑和查詢用戶邏輯 * Created by macro on 2019/11/5. */ publicclass SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity httpSecurity) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity .authorizeRequests(); //不需要保護的資源路徑允許訪問 for (String url : ignoreUrlsConfig().getUrls()) { registry.antMatchers(url).permitAll(); } //允許跨域請求的OPTIONS請求 registry.antMatchers(HttpMethod.OPTIONS) .permitAll(); // 任何請求需要身份認證 registry.and() .authorizeRequests() .anyRequest() .authenticated() // 關閉跨站請求防護及不使用session .and() .csrf() .disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 自定義權限拒絕處理類 .and() .exceptionHandling() .accessDeniedHandler(restfulAccessDeniedHandler()) .authenticationEntryPoint(restAuthenticationEntryPoint()) // 自定義權限攔截器JWT過濾器 .and() .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()) .passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { returnnew BCryptPasswordEncoder(); } @Bean public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() { returnnew JwtAuthenticationTokenFilter(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { returnsuper.authenticationManagerBean(); } @Bean public RestfulAccessDeniedHandler restfulAccessDeniedHandler() { returnnew RestfulAccessDeniedHandler(); } @Bean public RestAuthenticationEntryPoint restAuthenticationEntryPoint() { returnnew RestAuthenticationEntryPoint(); } @Bean public IgnoreUrlsConfig ignoreUrlsConfig() { returnnew IgnoreUrlsConfig(); } @Bean public JwtTokenUtil jwtTokenUtil() { returnnew JwtTokenUtil(); } }
關于“Java SpringSecurity+JWT如何實現登錄認證”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Java SpringSecurity+JWT如何實現登錄認證”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。