基于SpringBoot整合oauth2實(shí)現(xiàn)token認(rèn)證
這篇文章主要介紹了基于SpringBoot整合oauth2實(shí)現(xiàn)token 認(rèn)證,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
session和token的區(qū)別:
- session是空間換時(shí)間,而token是時(shí)間換空間。session占用空間,但是可以管理過(guò)期時(shí)間,token管理部了過(guò)期時(shí)間,但是不占用空間.
- sessionId失效問(wèn)題和token內(nèi)包含。
- session基于cookie,app請(qǐng)求并沒(méi)有cookie 。
- token更加安全(每次請(qǐng)求都需要帶上)
Oauth2 密碼授權(quán)流程
在oauth2協(xié)議里,每一個(gè)應(yīng)用都有自己的一個(gè)clientId和clientSecret(需要去認(rèn)證方申請(qǐng)),所以一旦想通過(guò)認(rèn)證,必須要有認(rèn)證方下發(fā)的clientId和secret。
1. pom
<!--security--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency>
2. UserDetail實(shí)現(xiàn)認(rèn)證第一步
MyUserDetailsService.java
@Autowired private PasswordEncoder passwordEncoder; /** * 根據(jù)進(jìn)行登錄 * @param username * @return * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("登錄用戶名:"+username); String password = passwordEncoder.encode("123456"); //User三個(gè)參數(shù) (用戶名+密碼+權(quán)限) //根據(jù)查找到的用戶信息判斷用戶是否被凍結(jié) log.info("數(shù)據(jù)庫(kù)密碼:"+password); return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); }
3. 獲取token的控制器
@RestController public class OauthController { @Autowired private ClientDetailsService clientDetailsService; @Autowired private AuthorizationServerTokenServices authorizationServerTokenServices; @Autowired private AuthenticationManager authenticationManager; @PostMapping("/oauth/getToken") public Object getToken(@RequestParam String username, @RequestParam String password, HttpServletRequest request) throws IOException { Map<String,Object>map = new HashMap<>(8); //進(jìn)行驗(yàn)證 String header = request.getHeader("Authorization"); if (header == null && !header.startsWith("Basic")) { map.put("code",500); map.put("message","請(qǐng)求投中無(wú)client信息"); return map; } String[] tokens = this.extractAndDecodeHeader(header, request); assert tokens.length == 2; //獲取clientId 和 clientSecret String clientId = tokens[0]; String clientSecret = tokens[1]; //獲取 ClientDetails ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); if (clientDetails == null){ map.put("code",500); map.put("message","clientId 不存在"+clientId); return map; //判斷 方言 是否一致 }else if (!StringUtils.equals(clientDetails.getClientSecret(),clientSecret)){ map.put("code",500); map.put("message","clientSecret 不匹配"+clientId); return map; } //使用username、密碼進(jìn)行登錄 UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password); //調(diào)用指定的UserDetailsService,進(jìn)行用戶名密碼驗(yàn)證 Authentication authenticate = authenticationManager.authenticate(authentication); HrUtils.setCurrentUser(authenticate); //放到session中 //密碼授權(quán) 模式, 組建 authentication TokenRequest tokenRequest = new TokenRequest(new HashMap<>(),clientId,clientDetails.getScope(),"password"); OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails); OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request,authentication); OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication); map.put("code",200); map.put("token",token.getValue()); map.put("refreshToken",token.getRefreshToken()); return map; } /** * 解碼請(qǐng)求頭 */ private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException { byte[] base64Token = header.substring(6).getBytes("UTF-8"); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (IllegalArgumentException var7) { throw new BadCredentialsException("Failed to decode basic authentication token"); } String token = new String(decoded, "UTF-8"); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } else { return new String[]{token.substring(0, delim), token.substring(delim + 1)}; } } }
4. 核心配置
(1)、Security 配置類 說(shuō)明登錄方式、登錄頁(yè)面、哪個(gè)url需要認(rèn)證、注入登錄失敗/成功過(guò)濾器
@Configuration public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter { /** * 注入 自定義的 登錄成功處理類 */ @Autowired private MyAuthenticationSuccessHandler mySuccessHandler; /** * 注入 自定義的 登錄失敗處理類 */ @Autowired private MyAuthenticationFailHandler myFailHandler; @Autowired private ValidateCodeFilter validateCodeFilter; /** * 重寫PasswordEncoder 接口中的方法,實(shí)例化加密策略 * @return 返回 BCrypt 加密策略 */ @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { //在UsernamePasswordAuthenticationFilter 過(guò)濾器前 加一個(gè)過(guò)濾器 來(lái)搞驗(yàn)證碼 http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) //表單登錄 方式 .formLogin() .loginPage("/authentication/require") //登錄需要經(jīng)過(guò)的url請(qǐng)求 .loginProcessingUrl("/authentication/form") .passwordParameter("pwd") .usernameParameter("user") .successHandler(mySuccessHandler) .failureHandler(myFailHandler) .and() //請(qǐng)求授權(quán) .authorizeRequests() //不需要權(quán)限認(rèn)證的url .antMatchers("/oauth/*","/authentication/*","/code/image").permitAll() //任何請(qǐng)求 .anyRequest() //需要身份認(rèn)證 .authenticated() .and() //關(guān)閉跨站請(qǐng)求防護(hù) .csrf().disable(); //默認(rèn)注銷地址:/logout http.logout(). //注銷之后 跳轉(zhuǎn)的頁(yè)面 logoutSuccessUrl("/authentication/require"); } /** * 認(rèn)證管理 * * @return 認(rèn)證管理對(duì)象 * @throws Exception 認(rèn)證異常信息 */ @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
(2)、認(rèn)證服務(wù)器
@Configuration @EnableAuthorizationServer public class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private MyUserDetailsService userDetailsService; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { super.configure(security); } /** * 客戶端配置(給誰(shuí)發(fā)令牌) * @param clients * @throws Exception */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory().withClient("internet_plus") .secret("internet_plus") //有效時(shí)間 2小時(shí) .accessTokenValiditySeconds(72000) //密碼授權(quán)模式和刷新令牌 .authorizedGrantTypes("refresh_token","password") .scopes( "all"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .userDetailsService(userDetailsService); } }
@EnableResourceServer這個(gè)注解就決定了這是個(gè)資源服務(wù)器。它決定了哪些資源需要什么樣的權(quán)限。
5、測(cè)試
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot3.X配置OAuth的代碼實(shí)踐
- SpringBoot的Security和OAuth2的使用示例小結(jié)
- 使用Springboot實(shí)現(xiàn)OAuth服務(wù)的示例詳解
- SpringBoot淺析安全管理之OAuth2框架
- springboot oauth2實(shí)現(xiàn)單點(diǎn)登錄實(shí)例
- springboot集成springsecurity 使用OAUTH2做權(quán)限管理的教程
- springboot2.x實(shí)現(xiàn)oauth2授權(quán)碼登陸的方法
- 詳解Springboot Oauth2 Server搭建Oauth2認(rèn)證服務(wù)
- 使用Springboot搭建OAuth2.0 Server的方法示例
- SpringBoot集成OAuth2.0的實(shí)現(xiàn)示例
相關(guān)文章
SpringBoot+Vue+Redis實(shí)現(xiàn)單點(diǎn)登錄(一處登錄另一處退出登錄)
小編接到一個(gè)需求,需要實(shí)現(xiàn)用戶在瀏覽器登錄后,跳轉(zhuǎn)到其他頁(yè)面,當(dāng)用戶在其它地方又登錄時(shí),前面用戶登錄的頁(yè)面退出登錄,這篇文章主要介紹了SpringBoot+Vue+Redis實(shí)現(xiàn)單點(diǎn)登錄,需要的朋友可以參考下2019-12-12淺談spring-boot 允許接口跨域并實(shí)現(xiàn)攔截(CORS)
本篇文章主要介紹了淺談spring-boot 允許接口跨域并實(shí)現(xiàn)攔截(CORS),具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08解決nacos的yml配置文件解析@開頭的值啟動(dòng)報(bào)錯(cuò)問(wèn)題
這篇文章主要介紹了解決nacos的yml配置文件解析@開頭的值啟動(dòng)報(bào)錯(cuò)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07Java詳解entity轉(zhuǎn)換到vo過(guò)程
這篇文章將用實(shí)例來(lái)和大家介紹一下entity轉(zhuǎn)換到vo的方法過(guò)程。文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Java有一定的幫助,需要的可以參考一下2022-06-06Java中引用類型之強(qiáng)引用、軟引用、弱引用和虛引用詳解
這篇文章主要介紹了Java中引用類型之強(qiáng)引用、軟引用、弱引用和虛引用的相關(guān)資料,通過(guò)實(shí)際代碼示例,展示了如何利用引用隊(duì)列來(lái)跟蹤對(duì)象的回收狀態(tài),并實(shí)現(xiàn)資源的自動(dòng)清理,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-03-03