如何实现单点登录系统的源码开发?

单点登录(SSO)源码是一种用于实现用户在多个应用间无缝切换的认证机制。

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

(0)
未希的头像未希新媒体运营
上一篇 2024-10-01 11:27
下一篇 2024-10-01 11:30

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入