1. 初始化数据库
在项目的资源目录下,创建四个SQL脚本以初始化用户和OAuth相关的表。
oauth_schema.sql DROP TABLE IF EXISTS oauth_client_details; CREATE TABLE oauth_client_details ( client_id VARCHAR(255) PRIMARY KEY, resource_ids VARCHAR(255), client_secret VARCHAR(255), scope VARCHAR(255), authorized_grant_types VARCHAR(255), web_server_redirect_uri VARCHAR(255), authorities VARCHAR(255), access_token_validity INTEGER, refresh_token_validity INTEGER, additional_information VARCHAR(4096), autoapprove VARCHAR(255) ); oauth_data.sql INSERT INTO oauth_client_details (client_id, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove) VALUES ('clientapp', '112233', 'read_userinfo,read_contacts', 'password,authorization_code,refresh_token', 'http://127.0.0.1:9090/login', null, 3600, 864000, null, true);
2. Spring Security OAuth2 配置
application.yml
在src/main/resources
目录下创建application.yml
文件,配置数据库和Redis信息:
spring: datasource: url: jdbc:mysql://localhost:3306/permission?serverTimezone=UTC username: root password: 123456 driverclassname: com.mysql.cj.jdbc.Driver jpa: showsql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL5Dialect session: storetype: redis redis: host: 127.0.0.1 port: 6379 port: 8080
AuthorizationServerConfig.java
创建一个AuthorizationServerConfig
类,用于配置OAuth2认证服务器:
package com.example.sso.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.checkTokenAccess("permitAll()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("clientapp") .secret("112233") .scopes("read_userinfo", "read_contacts") .authorizedGrantTypes("password", "authorization_code", "refresh_token") .redirectUris("http://127.0.0.1:9090/login") .autoApprove(true); } }
3. SSO服务实现
SsoServerApplication.java
创建SsoServerApplication
类,启动Spring Boot应用:
package com.example.sso; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; @SpringBootApplication @EnableEurekaClient @EnableResourceServer @EnableOAuth2Client public class SsoServerApplication { public static void main(String[] args) { SpringApplication.run(SsoServerApplication.class, args); } }
4. 页面和控制器实现
login.html
在src/main/resources/templates
目录下创建login.html
文件:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF8"> <title>登录页面</title> </head> <body> <form action="/ssoserver/sso/login" method="post"> <input name="url" type="hidden" th:value="${url}"/> 用户名:<input name="username" type="text"/> 密码:<input name="password" type="password"/> <input value="登录" type="submit"/> </form> </body> </html>
SsoController.java
创建SsoController
类,处理登录请求:
package com.example.sso.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import redis.clients.jedis.Jedis; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.util.UUID; @Controller public class SsoController { @Autowired private Jedis jedis; @GetMapping("/sso/loginPage") public ModelAndView loginPage(@RequestParam("url") String url) { ModelAndView modelAndView = new ModelAndView("login"); modelAndView.addObject("url", url); return modelAndView; } @PostMapping("/sso/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("url") String url, HttpServletResponse response) { // 校验用户名和密码的逻辑,此处简化为硬编码的用户和密码 if ("huanzi".equals(username) && "123456".equals(password)) { String accessToken = UUID.randomUUID().toString(); // 生成令牌,实际应用中应使用更复杂的生成方式 jedis.set(accessToken, username); // 将令牌存储到Redis中,并设置过期时间 Cookie cookie = new Cookie("accessToken", accessToken); cookie.setMaxAge(3 * 60); // 设置cookie有效期为3分钟 cookie.setPath("/"); response.addCookie(cookie); return "redirect:" + url; // 重定向回原始请求的URL } else { return "redirect:/sso/loginPage?url=" + url; // 登录失败,重定向回登录页面 } } }
5. 归纳与扩展阅读
通过上述步骤,我们实现了一个基本的单点登录系统,包括数据库初始化、Spring Security OAuth2配置、SSO服务实现以及页面和控制器的实现,还可以参考以下资源进一步学习:
[Spring Security官方文档](https://docs.spring.io/springsecurity/site/docs/current/reference/html5/)
[OAuth 2.0官方规范](https://tools.ietf.org/html/rfc6749)
到此,以上就是小编对于单点登录 源码的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1115738.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复