最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

前言:

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

整合步驟

這里我們以mall-portal改造為例來(lái)說(shuō)說(shuō)如何實(shí)現(xiàn)。

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

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

第二步,添加MallSecurityConfig配置類,繼承mall-security中的SecurityConfig配置,并且配置一個(gè)UserDetailsService接口的實(shí)現(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中實(shí)現(xiàn)登錄和刷新token的接口:

/**
 * 會(huì)員登錄注冊(cè)管理Controller
 * Created by macro on 2018/8/3.
 */
@Controller
@Api(tags = "UmsMemberController", description = "會(huì)員登錄注冊(cè)管理")
@RequestMapping("/sso")
publicclass UmsMemberController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsMemberService memberService;

    @ApiOperation("會(huì)員登錄")
    @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("用戶名或密碼錯(cuò)誤");
        }
        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)過(guò)期!");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }
}

實(shí)現(xiàn)原理

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

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

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

做了哪些變化

其實(shí)我也就添加了兩個(gè)類,一個(gè)IgnoreUrlsConfig,用于從application.yml中獲取不需要安全保護(hù)的資源路徑。一個(gè)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中的代碼:

/**
 * 對(duì)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ù)的資源路徑允許訪問(wèn)
        for (String url : ignoreUrlsConfig().getUrls()) {
            registry.antMatchers(url).permitAll();
        }
        //允許跨域請(qǐng)求的OPTIONS請(qǐng)求
        registry.antMatchers(HttpMethod.OPTIONS)
                .permitAll();
        // 任何請(qǐng)求需要身份認(rèn)證
        registry.and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                // 關(guān)閉跨站請(qǐng)求防護(hù)及不使用session
                .and()
                .csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 自定義權(quán)限拒絕處理類
                .and()
                .exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler())
                .authenticationEntryPoint(restAuthenticationEntryPoint())
                // 自定義權(quán)限攔截器JWT過(guò)濾器
                .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實(shí)現(xiàn)登錄認(rèn)證 的文章就介紹到這了,更多相關(guān)Java SpringSecurity 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • javaweb在線支付功能實(shí)現(xiàn)代碼

    javaweb在線支付功能實(shí)現(xiàn)代碼

    這篇文章主要為大家詳細(xì)介紹了javaweb在線支付功能的實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • JAVA生成八位不重復(fù)隨機(jī)數(shù)最快的方法總結(jié)(省時(shí)間省空間)

    JAVA生成八位不重復(fù)隨機(jī)數(shù)最快的方法總結(jié)(省時(shí)間省空間)

    隨機(jī)數(shù)在實(shí)際中使用很廣泛,比如要隨即生成一個(gè)固定長(zhǎng)度的字符串、數(shù)字,這篇文章主要給大家介紹了關(guān)于JAVA生成八位不重復(fù)隨機(jī)數(shù)最快的方法,文中介紹的方法省時(shí)間省空間,需要的朋友可以參考下
    2024-03-03
  • SpringBoot整合RabbitMQ實(shí)現(xiàn)六種工作模式的示例

    SpringBoot整合RabbitMQ實(shí)現(xiàn)六種工作模式的示例

    這篇文章主要介紹了SpringBoot整合RabbitMQ實(shí)現(xiàn)六種工作模式,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • 解決mybatisPlus null 值更新的問(wèn)題

    解決mybatisPlus null 值更新的問(wèn)題

    這篇文章主要介紹了解決mybatisPlus null 值更新的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • Invalid bound statement(not found):錯(cuò)誤的解決方案

    Invalid bound statement(not found):錯(cuò)誤的解決方案

    本文介紹了在開(kāi)發(fā)Java SpringBoot應(yīng)用程序時(shí)出現(xiàn)的"Invalidboundstatement(notfound)"錯(cuò)誤的原因及解決方法,該錯(cuò)誤通常與MyBatis或其他持久化框架相關(guān),可能是由于配置錯(cuò)誤、拼寫錯(cuò)誤或其他問(wèn)題引起的,解決方法包括檢查SQL映射文件
    2025-01-01
  • Maven重復(fù)依賴問(wèn)題解決(同一個(gè)jar多個(gè)版本)

    Maven重復(fù)依賴問(wèn)題解決(同一個(gè)jar多個(gè)版本)

    本文主要介紹了Maven重復(fù)依賴問(wèn)題解決(同一個(gè)jar多個(gè)版本),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼

    Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼

    這篇文章主要介紹了Spring+Quartz配置定時(shí)任務(wù)實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • SpringBoot集成緩存功能詳解

    SpringBoot集成緩存功能詳解

    Java?Caching定義了五個(gè)核心接口,分別是:CachingProvider、CacheManager、Cache、Entry和Expiry,這篇文章主要介紹了SpringBoot集成緩存功能詳細(xì)過(guò)程,需要的朋友可以參考下
    2024-06-06
  • mybatis中批量插入的兩種方式(高效插入)

    mybatis中批量插入的兩種方式(高效插入)

    MyBatis是一個(gè)支持普通SQL查詢,存儲(chǔ)過(guò)程和高級(jí)映射的優(yōu)秀持久層框架。這篇文章主要介紹了mybatis中批量插入的兩種方式(高效插入)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起看看吧
    2016-09-09
  • java基礎(chǔ)理論Stream管道流Map操作示例

    java基礎(chǔ)理論Stream管道流Map操作示例

    這篇文章主要未大家介紹了java基礎(chǔ)理論Stream管道流Map操作方法示例解析,有需要的朋友可以借鑒參考下希望能夠有所幫助,祝大家多多進(jìn)步
    2022-03-03

最新評(píng)論

民勤县| 定襄县| 建德市| 夏河县| 东乌| 通州区| 新龙县| 桃江县| 兰溪市| 崇仁县| 曲阜市| 庆云县| 奉节县| 阿巴嘎旗| 司法| 仙桃市| 泊头市| 汉川市| 武威市| 高雄市| 漳浦县| 潼南县| 乌海市| 屏东市| 买车| 通州市| 惠来县| 临颍县| 喜德县| 株洲县| 江口县| 景洪市| 南皮县| 廉江市| 青龙| 湘潭市| 兴安盟| 平武县| 灵宝市| 金塔县| 安化县|