(流程图 + 代码)带你实现单点登陆SSO(二)

简介: (流程图 + 代码)带你实现单点登陆SSO

4.4. WebSecurityConfig(重要)

package com.cjs.sso.config;
import com.cjs.sso.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
 * @author ChengJianSheng
 * @date 2019-02-11
 */
@Configuration
@EnableWebSecurity
publicclass WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/assets/**", "/css/**", "/images/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login")
                .and()
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest()
                .authenticated()
                .and().csrf().disable().cors();
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        returnnew BCryptPasswordEncoder();
    }
}

4.5. 自定义登录页面(一般来讲都是要自定义的)

package com.cjs.sso.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
/**
 * @author ChengJianSheng
 * @date 2019-02-12
 */
@Controller
publicclass LoginController {
    @GetMapping("/login")
    public String login() {
        return"login";
    }
    @GetMapping("/")
    public String index() {
        return"index";
    }
}

自定义登录页面的时候,只需要准备一个登录页面,然后写个Controller令其可以访问到即可,登录页面表单提交的时候method一定要是post,最重要的时候action要跟访问登录页面的url一样

千万记住了,访问登录页面的时候是GET请求,表单提交的时候是POST请求,其它的就不用管了

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Ela Admin - HTML5 Admin Template</title>
    <meta name="description" content="Ela Admin - HTML5 Admin Template">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link type="text/css" rel="stylesheet" th:href="@{/assets/css/normalize.css}">
    <link type="text/css" rel="stylesheet" th:href="@{/assets/bootstrap-4.3.1-dist/css/bootstrap.min.css}">
    <link type="text/css" rel="stylesheet" th:href="@{/assets/css/font-awesome.min.css}">
    <link type="text/css" rel="stylesheet" th:href="@{/assets/css/style.css}">
</head>
<body class="bg-dark">
<div class="sufee-login d-flex align-content-center flex-wrap">
    <div class="container">
        <div class="login-content">
            <div class="login-logo">
                <h1 style="color: #57bf95;">欢迎来到王者荣耀</h1>
            </div>
            <div class="login-form">
                <form th:action="@{/login}" method="post">
                    <div class="form-group">
                        <label>Username</label>
                        <input type="text" class="form-control" name="username" placeholder="Username">
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" class="form-control" name="password" placeholder="Password">
                    </div>
                    <div class="checkbox">
                        <label>
                            <input type="checkbox"> Remember Me
                        </label>
                        <label class="pull-right">
                            <a href="#">Forgotten Password?</a>
                        </label>
                    </div>
                    <button type="submit" class="btn btn-success btn-flat m-b-30 m-t-30" style="font-size: 18px;">登录</button>
                </form>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" th:src="@{/assets/js/jquery-2.1.4.min.js}"></script>
<script type="text/javascript" th:src="@{/assets/bootstrap-4.3.1-dist/js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{/assets/js/main.js}"></script>
</body>
</html>

4.6. 定义客户端

bfbd7c2bdcb0b4eb8e7afdafbf4553aa_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.pnga59983fcc206e2d153b1f0fda4d31ff4_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.png

4.7. 加载用户

登录账户

package com.cjs.sso.domain;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
/**
 * 大部分时候直接用User即可不必扩展
 * @author ChengJianSheng
 * @date 2019-02-11
 */
@Data
publicclass MyUser extends User {
    private Integer departmentId;   //  举个例子,部门ID
    private String mobile;  //  举个例子,假设我们想增加一个字段,这里我们增加一个mobile表示手机号
    public MyUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }
    public MyUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
}

加载登录账户

package com.cjs.sso.service;
import com.alibaba.fastjson.JSON;
import com.cjs.sso.domain.MyUser;
import com.cjs.sso.entity.SysPermission;
import com.cjs.sso.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * @author ChengJianSheng
 * @date 2019-02-11
 */
@Slf4j
@Service
publicclass MyUserDetailsService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getByUsername(username);
        if (null == sysUser) {
            log.warn("用户{}不存在", username);
            thrownew UsernameNotFoundException(username);
        }
        List<SysPermission> permissionList = permissionService.findByUserId(sysUser.getId());
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissionList)) {
            for (SysPermission sysPermission : permissionList) {
                authorityList.add(new SimpleGrantedAuthority(sysPermission.getCode()));
            }
        }
        MyUser myUser = new MyUser(sysUser.getUsername(), passwordEncoder.encode(sysUser.getPassword()), authorityList);
        log.info("登录成功!用户: {}", JSON.toJSONString(myUser));
        return myUser;
    }
}

4.8. 验证

dd8932f7fba09f78e5118e6e5983121f_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.png

当我们看到这个界面的时候,表示认证服务器配置完成


相关文章
|
6月前
|
NoSQL Redis
SSO单点登录核心原理
SSO单点登录核心原理
164 0
|
JavaScript 前端开发 PHP
什么是单点登录,单点登录的逻辑,思路,
什么是单点登录,单点登录的逻辑,思路,
202 0
|
6月前
|
监控 安全 数据安全/隐私保护
探索 SSO 的世界:简化登录流程的最佳实践(下)
探索 SSO 的世界:简化登录流程的最佳实践(下)
探索 SSO 的世界:简化登录流程的最佳实践(下)
|
6月前
|
存储 缓存
实现单点登录的方式
实现单点登录的方式
91 1
|
6月前
|
存储 缓存 数据安全/隐私保护
探索 SSO 的世界:简化登录流程的最佳实践(上)
探索 SSO 的世界:简化登录流程的最佳实践(上)
探索 SSO 的世界:简化登录流程的最佳实践(上)
|
安全 数据安全/隐私保护
单点登录(SSO)看这一篇就够了
单点登录(SSO)看这一篇就够了
1062 4
|
存储 安全 Java
(流程图 + 代码)带你实现单点登陆SSO(一)
(流程图 + 代码)带你实现单点登陆SSO
|
移动开发 安全 前端开发
(流程图 + 代码)带你实现单点登陆SSO(三)
(流程图 + 代码)带你实现单点登陆SSO
|
敏捷开发 开发框架 JSON
一看就懂的IdentityServer4认证授权设计方案
一看就懂的IdentityServer4认证授权设计方案
|
存储 JSON 数据安全/隐私保护
Jasny SSO是如何实现的?底层原理是什么?
Jasny SSO是如何实现的?底层原理是什么?
120 0