亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java SpringSecurity+JWT實現(xiàn)登錄認(rèn)證

 更新時間:2022年06月10日 10:05:42   作者:夢想de星空  
這篇文章主要介紹了Java SpringSecurity+JWT實現(xiàn)登錄認(rèn)證,首先通過給需要登錄認(rèn)證的模塊添加mall-security依賴展開介紹,感興趣的朋友可以參考一下

前言:

學(xué)習(xí)過我的mall項目的應(yīng)該知道,mall-admin模塊是使用SpringSecurity+JWT來實現(xiàn)登錄認(rèn)證的,而mall-portal模塊是使用的SpringSecurity基于Session的默認(rèn)機(jī)制來實現(xiàn)登陸認(rèn)證的。很多小伙伴都找不到mall-portal的登錄接口,最近我把這兩個模塊的登錄認(rèn)證給統(tǒng)一了,都使用SpringSecurity+JWT的形式實現(xiàn)。主要是通過把登錄認(rèn)證的通用邏輯抽取到了mall-security模塊來實現(xiàn)的,下面我們講講如何使用mall-security模塊來實現(xiàn)登錄認(rèn)證,僅需四步即可。

整合步驟

這里我們以mall-portal改造為例來說說如何實現(xiàn)。

第一步,給需要登錄認(rèn)證的模塊添加mall-security依賴:

<dependency>
    <groupId>com.macro.mall</groupId>
    <artifactId>mall-security</artifactId>
</dependency>

第二步,添加MallSecurityConfig配置類,繼承mall-security中的SecurityConfig配置,并且配置一個UserDetailsService接口的實現(xiàn)類,用于獲取登錄用戶詳情:

/**
 * mall-security模塊相關(guān)配置
 * 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中配置下不需要安全保護(hù)的資源路徑:

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中實現(xiàn)登錄和刷新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已經(jīng)過期!");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }
}

實現(xiàn)原理

將SpringSecurity+JWT的代碼封裝成通用模塊后,就可以方便其他需要登錄認(rèn)證的模塊來使用,下面我們來看看它是如何實現(xiàn)的,首先我們看下mall-security的目錄結(jié)構(gòu)。

目錄結(jié)構(gòu)

mall-security
├── component
|    ├── JwtAuthenticationTokenFilter -- JWT登錄授權(quán)過濾器
|    ├── RestAuthenticationEntryPoint -- 自定義返回結(jié)果:未登錄或登錄過期
|    └── RestfulAccessDeniedHandler -- 自定義返回結(jié)果:沒有權(quán)限訪問時
├── config
|    ├── IgnoreUrlsConfig -- 用于配置不需要安全保護(hù)的資源路徑
|    └── SecurityConfig -- SpringSecurity通用配置
└── util
     └── JwtTokenUtil -- JWT的token處理工具類

做了哪些變化

其實我也就添加了兩個類,一個IgnoreUrlsConfig,用于從application.yml中獲取不需要安全保護(hù)的資源路徑。一個SecurityConfig提取了一些SpringSecurity的通用配置。

IgnoreUrlsConfig中的代碼:

/**
 * 用于配置不需要保護(hù)的資源路徑
 * Created by macro on 2018/11/5.
 */
@Getter
@Setter
@ConfigurationProperties(prefix = "secure.ignored")
publicclass IgnoreUrlsConfig {

    private List<String> urls = new ArrayList<>();

}

SecurityConfig中的代碼:

/**
 * 對SpringSecurity的配置的擴(kuò)展,支持自定義白名單資源路徑和查詢用戶邏輯
 * 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();
        //不需要保護(hù)的資源路徑允許訪問
        for (String url : ignoreUrlsConfig().getUrls()) {
            registry.antMatchers(url).permitAll();
        }
        //允許跨域請求的OPTIONS請求
        registry.antMatchers(HttpMethod.OPTIONS)
                .permitAll();
        // 任何請求需要身份認(rèn)證
        registry.and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                // 關(guān)閉跨站請求防護(hù)及不使用session
                .and()
                .csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 自定義權(quán)限拒絕處理類
                .and()
                .exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler())
                .authenticationEntryPoint(restAuthenticationEntryPoint())
                // 自定義權(quán)限攔截器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();
    }
}

到此這篇關(guān)于Java SpringSecurity+JWT實現(xiàn)登錄認(rèn)證 的文章就介紹到這了,更多相關(guān)Java SpringSecurity 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot項目中出現(xiàn)同名bean異常報錯的解決方法

    springboot項目中出現(xiàn)同名bean異常報錯的解決方法

    這篇文章給大家聊聊springboot項目出現(xiàn)同名bean異常報錯如何修復(fù),文中通過代碼示例給大家介紹解決方法非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-01-01
  • springboot 接口版本區(qū)分方式

    springboot 接口版本區(qū)分方式

    這篇文章主要介紹了springboot 接口版本區(qū)分方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • java?Spring?Boot的介紹與初體驗

    java?Spring?Boot的介紹與初體驗

    大家好,本篇文章主要講的是java?Spring?Boot的介紹與初體驗,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-01-01
  • java獲取類名的方法詳解

    java獲取類名的方法詳解

    這篇文章主要介紹了java獲取類名的問題詳解,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-07-07
  • MybatisPlusInterceptor依賴變紅如何解決,無法識別問題

    MybatisPlusInterceptor依賴變紅如何解決,無法識別問題

    這篇文章主要介紹了MybatisPlusInterceptor依賴變紅如何解決,無法識別問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • Java 反射(Reflect)詳解

    Java 反射(Reflect)詳解

    這篇文章主要介紹了JAVA 反射機(jī)制的相關(guān)知識,文中講解的非常細(xì)致,代碼幫助大家更好的理解學(xué)習(xí),感興趣的朋友可以了解下
    2021-09-09
  • 一文教會你使用jmap和MAT進(jìn)行堆內(nèi)存溢出分析

    一文教會你使用jmap和MAT進(jìn)行堆內(nèi)存溢出分析

    本文介紹關(guān)于jmap和MAT的使用來進(jìn)行堆內(nèi)存溢出分析,因為這個內(nèi)存溢出是我們手動構(gòu)造出來的,查找比較簡單,真的到了生產(chǎn)上面需要我們仔細(xì)排除
    2021-09-09
  • Java編程調(diào)用微信支付功能的方法詳解

    Java編程調(diào)用微信支付功能的方法詳解

    這篇文章主要介紹了Java編程調(diào)用微信支付功能的方法,結(jié)合實例形式詳細(xì)分析了java微信支付功能的原理、操作流程及相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2017-08-08
  • Java中的switch新特性與使用詳解

    Java中的switch新特性與使用詳解

    這篇文章主要介紹了Java中的switch新特性與使用詳解,Switch語句可以實現(xiàn)根據(jù)某一變量選則執(zhí)行代碼塊,當(dāng)然直接使用If語句也可以做到,但是有時候使用Switch語句往往更加簡潔優(yōu)美,需要的朋友可以參考下
    2023-11-11
  • Java中的位運(yùn)算符、移位運(yùn)算詳細(xì)介紹

    Java中的位運(yùn)算符、移位運(yùn)算詳細(xì)介紹

    這篇文章主要介紹了Java中的位運(yùn)算符、移位運(yùn)算,有需要的朋友可以參考一下
    2013-12-12

最新評論