第一种:  简单的  推荐   springboot 2++

只需要三个文件 application.yml     controller    POM

1) application.yml

okta:
  oauth2:
    issuer: https://dev-482025.oktapreview.com/oauth2/default
    client-id: 0oaidl07zh1iY9KeM0h7
    client-secret: QkVS1UIZCZab59_f4tavzDuzfb9Ead6jNxezMuR7

2) POM  依赖

<dependency>
    <groupId>com.okta.spring</groupId>
    <artifactId>okta-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.okta.spring/okta-spring-sdk -->
<dependency>
    <groupId>com.okta.spring</groupId>
    <artifactId>okta-spring-sdk</artifactId>
    <version>1.0.0</version>
</dependency>

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

3) 测试controller

@RestController
public class HelloController {
    @RequestMapping("/okta/test")
    String home() {
        return "home";
    }
    
    @GetMapping("/")
    public String getMessageOfTheDay(Principal principal) {
        return principal.getName() + ", this message of the day is boring";
    }
}

4) 启动类当然不能少

@SpringBootApplication
public class OktaDemo2Application {

public static void main(String[] args) {
        SpringApplication.run(OktaDemo2Application.class, args);
    }
    
    @Configuration
    static class OktaOAuth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

@Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests().anyRequest().authenticated()
                .and().oauth2Client().and()
                .oauth2Login()/*.and()
                .oauth2ResourceServer().jwt()*/;
        }
    }

}

第二种:

package com.example.oktademo.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;@Configuration
public class OAuth2LoginConfig {@EnableWebSecuritypublic static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().oauth2Login();}}}

上面是配置文件,下面是 application.yml 文件

server:port: 8080logging:level:root: INFOorg.springframework.web: INFOorg.springframework.security: INFO
#    org.springframework.boot.autoconfigure: DEBUGspring:thymeleaf:cache: falsesecurity:oauth2:client:registration:          okta:client-id: 0oaie481w6oiaN8Tk0h7client-secret: 9sDR2NO4k0Rh-M23HfzQzKYmjn-NJ9vkoJwadvhCclient-name: Okta Login Testprovider:okta:authorization-uri: https://dev-482025.oktapreview.com/oauth2/v1/authorizetoken-uri: https://dev-482025.oktapreview.com/oauth2/v1/tokenuser-info-uri: https://dev-482025.oktapreview.com/oauth2/v1/userinfojwk-set-uri: https://dev-482025.oktapreview.com/oauth2/v1/keys 

第三: 这个是controller 文件

package com.example.oktademo.controller;import java.util.Collections;
import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;import reactor.core.publisher.Mono;@Controller
public class OAuth2Controller {@Autowiredprivate OAuth2AuthorizedClientService authorizedClientService;@RequestMapping("/")public String index(Model model, OAuth2AuthenticationToken authentication) {OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);model.addAttribute("userName", authentication.getName());model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());return "index";}private OAuth2AuthorizedClient getAuthorizedClient(OAuth2AuthenticationToken authentication) {return this.authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());}@RequestMapping("/userinfo")public String userinfo(Model model,OAuth2AuthenticationToken authentication) {// authentication.getAuthorizedClientRegistrationId() returns the// registrationId of the Client that was authorized during the Login flowOAuth2AuthorizedClient authorizedClient =this.authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(),authentication.getName());OAuth2AccessToken accessToken = authorizedClient.getAccessToken();System.out.println(accessToken.getTokenValue());Map userAttributes = Collections.emptyMap();String userInfoEndpointUri = authorizedClient.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();if (!StringUtils.isEmpty(userInfoEndpointUri)) {// userInfoEndpointUri is optional for OIDC ClientsuserAttributes = WebClient.builder().filter(oauth2Credentials(authorizedClient)).build().get().uri(userInfoEndpointUri).retrieve().bodyToMono(Map.class).block();}model.addAttribute("userAttributes", userAttributes);return "userinfo";}private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) {return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {ClientRequest authorizedRequest = ClientRequest.from(clientRequest).header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue()).build();return Mono.just(authorizedRequest);});}
}

第四:   POM文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>okta-demo</artifactId><version>0.0.1-SNAPSHOT</version><name>okta-demo</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version></parent><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity4</artifactId><version>2.1.2.RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!-- https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure --><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId><version>2.0.1.RELEASE</version></dependency><!-- <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> --><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-client</artifactId></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-jose</artifactId></dependency><dependency><groupId>com.okta.spring</groupId><artifactId>okta-spring-boot-starter</artifactId><version>0.6.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>io.projectreactor</groupId><artifactId>reactor-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build><pluginRepositories><pluginRepository><id>spring-snapshots</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><snapshots><enabled>true</enabled></snapshots></pluginRepository><pluginRepository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></pluginRepository></pluginRepositories></project>

第五:  resources 源文件下面新建一个templates文件夹放入index.html 和userinfo.html

1) index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head><title>Spring Security - OAuth2 Login</title><meta charset="utf-8" />
</head>
<body>
<div style="float: right" th:fragment="logout" sec:authorize="isAuthenticated()"><div style="float:left"><span style="font-weight:bold">User: </span><span sec:authentication="name"></span></div><div style="float:none">&nbsp;</div><div style="float:right"><form action="#" th:action="@{/logout}" method="post"><input type="submit" value="Logout" /></form></div>
</div>
<h1>OAuth2 Login with Spring Security</h1>
<div>You are successfully logged in <span style="font-weight:bold" th:text="${userName}"></span>via the OAuth2 Client <span style="font-weight:bold" th:text="${clientName}"></span>
</div>
<div>&nbsp;</div>
<div><a href="/userinfo" th:href="@{/userinfo}">Display User Information</a>
</div>
</body>
</html>

2) userinfo.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head><title>Spring Security - OAuth2 User Information</title><meta charset="utf-8" />
</head>
<body>
<div th:substituteby="index::logout"></div>
<h1>OAuth2 User Information</h1>
<div><span style="font-weight:bold">User Attributes:</span><ul><li th:each="userAttribute : ${userAttributes}"><span style="font-weight:bold" th:text="${userAttribute.key}"></span>: <span th:text="${userAttribute.value}"></span></li></ul>
</div>
</body>
</html>

参考文章:

saml :       https://developer.okta.com/blog/2017/03/16/spring-boot-saml 或https://github.com/oktadeveloper/okta-spring-boot-saml-example

oauth2:     https://developer.okta.com/blog/2017/03/21/spring-boot-oauth

OKTA demo 推荐第一种相关推荐

  1. 如何删除CSDN上自己上传的资源方法汇总(第一种方法神操作,亲测有效)

    方法一: 第一步,找到你想删除的资源, 其URL举例为: http://download.csdn.net/download/qq_21794823/10041808 则删除的get请求为: http ...

  2. Core CLR 自定义的Host官方推荐的一种形式(第一种)

    Core CLR 自定义的Host官方推荐的一种形式(第一种) .Net Core CLR提供两种Host API访问 托管代码的形式,按照微软官方的说法,一种是通过CoreClr.DLL来直接调用托 ...

  3. 宇宙中至少有两种方式能灭绝人类,第一种仅需两秒

    来源:科学的乐园 在科幻小说<三体Ⅲ:死神永生>之中,歌者文明"母世界"的宇宙飞船曾经利用宇宙规律武器二向箔来摧毁地球文明,将地球所处的三维世界完全变成了一个二维世界. ...

  4. Spring整合Struts2框架的第一种方式(Action由Struts2框架来创建)。在我的上一篇博文中介绍的通过web工厂的方式获取servcie的方法因为太麻烦,所以开发的时候不会使用。...

    1. spring整合struts的基本操作见我的上一篇博文:https://www.cnblogs.com/wyhluckdog/p/10140588.html,这里面将spring与struts2 ...

  5. .net pdf转图片_图片转PDF怎么转?推荐两种图片转PDF方法

    在我们的工作和学习中,我们有时候需要将图片转换为PDF格式的文件.因为PDF格式的文件查看起来很不容易,所以它可以确保图片文件中的信息不被泄露.那么图片转PDF怎么转呢?大家可以参考下面这两种方法,一 ...

  6. java mvc中重复提交表单,spring mvc 防止重复提交表单的两种方法,推荐第二种

    第一种方法:判断session中保存的token 比较麻烦,每次在提交表单时都必须传入上次的token.而且当一个页面使用ajax时,多个表单提交就会有问题. 注解Token代码: package c ...

  7. 小程序完整demo推荐:东航旅行;预订酒店,机票(适用1221)

    这是东航电商的东航旅行的完整项目,很荣幸作为第一批吃螃蟹的人.目录结构 [AppleScript]  纯文本查看  复制代码 less --> less文件目录scripts --> 微信 ...

  8. 给不会打字的朋友推荐一种鼠标写字的输入法

    给不会打字的朋友推荐一种鼠标写字的输入法 2011年05月29日 软件名称:逍遥笔 软件版本:6.5 软件授权:免费软件 使用平台:NT/2000/XP/2003/Vista 插件情况:无插件 公司网 ...

  9. Win7怎么安装?推荐3种Windows7安装方法

    最近不少朋友在问Win7如何安装的问题,笔者在此推荐3种Windows7安装方法,包括了光盘安装法.U盘安装法和硬盘安装法.因为相关的Win7安装步骤分解文章已经另有文章,因此笔者在此做简单说说Win ...

最新文章

  1. 记录:SqlParamater要点小结
  2. Item9:总是要改写toString
  3. 面向对象之继承与派生
  4. 流程控制语句(bash)
  5. c#sql防注入模糊查询_SQL中利用LIKE实现模糊查询的功能
  6. Java基础学习总结(154)——Synchronized与Volatile、Synchronized与ReentrantLock概念及区别
  7. EBS 常用 SQL
  8. 为什么被喷的总是产品经理?
  9. 小米手机抓取Log教程
  10. [PAT B1020] 月饼
  11. Java三大特性之多态
  12. java实现冒泡排序
  13. canvas lineWidth为1时线条粗细和颜色
  14. Android 获取圆角图标bitmap黑色背景问题解决
  15. TypeScript 学习笔记(十万字超详细知识点总结)
  16. 第十二周项目5-迷宫问题之图深度优先遍历解法
  17. 华为的隐藏功能,你们知道多少?
  18. Bottom-Up and Top-Down
  19. Python核心编程(第3版)第2章网络编程中关于tcp/udp服务器和客户端实现代码的运行出错的修正
  20. SC系列 (SC-32S) 低频率小型SMD石英晶振 SC-32S 32.768KHZ 12.5PF/20PPM

热门文章

  1. 突变点检测:Mann-Kendall突变点检测(python)
  2. 蓝色简洁大学毕业生求职简历PPT模板
  3. 公有云长期战略合作协议,为其提供横跨设计、建设、运营的全生命周期服务的云计算解决方案,涵盖云基础设施即服务(IaaS)和平台即服务(PaaS)和软件即服务(SaaS)
  4. 2005年度《超级女声》冠军李宇春登上美国《时代周刊》而后的评论?
  5. 最新QQ2008贺岁协议分析第三版
  6. 【JavaSE】Collection 接口和常用方法
  7. php xml解析无值,PHP-XML解析-缺少节点
  8. 13. 内置函数和推导式
  9. linux下配置网络打印机
  10. 张泉灵“生命的后半段”读后感