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 public class 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() { return new 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 public class 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. 定义客户端
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 public class 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 public class 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); throw new 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. 验证
当我们看到这个界面的时候,表示认证服务器配置完成