idea整合简单的oauth2认证服务器和资源认证服务器
带认证的调用
无需认证的调用
项目整体目录结构
父类
<?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.qiuxie</groupId> <artifactId>qiuxie-parent</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>one-oauth-service</module> <module>eureka-service</module> <module>one-login-service</module> </modules> <!--spring boot 父启动器依赖--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> </parent> <properties> <eureka.version>2.1</eureka.version> <web.version>2.1.18.RELEASE</web.version> </properties> <!--用于整体控制依赖的版本--> <dependencyManagement> <dependencies> <!--spring cloud依赖管理,引入了Spring Cloud的版本--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.0.1.RELEASE</version> </dependency> <!--lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> </dependency> <!--导入Eureka Server依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> <version>2.0.0.RELEASE</version> </dependency> <!--客户端--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>2.0.0.RELEASE</version> </dependency> <!--引入security对oauth2的支持--> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.11.RELEASE</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <!--编译插件--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> <!--打包插件--> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
注册中心
<?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"> <parent> <artifactId>qiuxie-parent</artifactId> <groupId>com.qiuxie</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.eureka</groupId> <artifactId>eureka-service</artifactId> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies> </project> server.port=8761 spring.application.name=eureka-service eureka.instance.hostname=localhost eureka.client.service-url.defaultZone=http://localhost:8761/eureka eureka.client.register-with-eureka=false eureka.client.fetch-registry=false package com.eureka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * @author yourheart * @Description * @create 2022-02-14 20:33 */ @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class,args); } }
认证服务器
<?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"> <parent> <artifactId>qiuxie-parent</artifactId> <groupId>com.qiuxie</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>one.oauth</groupId> <artifactId>one-oauth-service</artifactId> <dependencies> <!--导入spring cloud oauth2依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> <exclusions> <exclusion> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> </dependency> <!--引入security对oauth2的支持--> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <!--客户端--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> </project> server.port=2000 spring.application.name=one-oauth #注册到eureka注册中心,如果是注册到集群就用逗号连接多个,单实例写上一个就好 eureka.client.service-url.defaultZone=http://localhost:8761/eureka logging.level.one.oauth=debug logging.level.web=debug spring.devtools.add-properties=false package one.oauth; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @author yourheart * @Description * @create 2022-02-14 20:38 */ @SpringBootApplication @EnableDiscoveryClient public class OneOauthApplication { public static void main(String[] args) { SpringApplication.run(OneOauthApplication.class,args); } } package one.oauth.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; 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.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; /** * @author yourheart * @Description * @create 2022-02-15 20:05 */ @Configuration @EnableAuthorizationServer //开启认证服务器功能 public class OauthServerConfiger extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { super.configure(security); security.allowFormAuthenticationForClients() .tokenKeyAccess("permitAll()") .checkTokenAccess("permitAll()"); } /** * 客户端详情配置 * @param clients * @throws Exception */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { super.configure(clients); clients.inMemory() .withClient("client_qiuxie") .secret("13301455191qiuxieM") .resourceIds("loginId") .authorizedGrantTypes("password","refresh_token") .scopes("all"); } /** * 配置token令牌相关 * @param endpoints * @throws Exception */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { super.configure(endpoints); endpoints.tokenStore(tokenStore()) .tokenServices(authorizationServerTokenServices()) .authenticationManager(authenticationManager) .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.GET); } public AuthorizationServerTokenServices authorizationServerTokenServices(){ DefaultTokenServices tokenServices = new DefaultTokenServices(); tokenServices.setSupportRefreshToken(true); tokenServices.setTokenStore(tokenStore()); tokenServices.setAccessTokenValiditySeconds(120);//令牌有效时间120s tokenServices.setRefreshTokenValiditySeconds(259200);//刷新令牌有效时间3天 return tokenServices; } public TokenStore tokenStore(){ return new InMemoryTokenStore(); } } package one.oauth.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.ArrayList; /** * @author yourheart * @Description * @create 2022-02-21 20:20 */ @Configuration public class SecurityConfiger extends WebSecurityConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; /** * 注册认证管理器到容器 * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * 密码编码器 * @return */ @Bean public PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } /** * 处理用户名和密码 * @param auth * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { UserDetails userDetails=new User("admin","13301455191qiuxieM",new ArrayList<>()); auth.inMemoryAuthentication() .withUser(userDetails).passwordEncoder(passwordEncoder); } }
资源服务器
<?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"> <parent> <artifactId>qiuxie-parent</artifactId> <groupId>com.qiuxie</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>one.login</groupId> <artifactId>one-login-service</artifactId> <dependencies> <!--导入spring cloud oauth2依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> <exclusions> <exclusion> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> </dependency> <!--引入security对oauth2的支持--> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <!--客户端--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!--web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> </project> server.port=2001 spring.application.name=one-login #注册到eureka注册中心,如果是注册到集群就用逗号连接多个,单实例写上一个就好 eureka.client.service-url.defaultZone=http://localhost:8761/eureka logging.level.one.login=debug logging.level.web=debug spring.devtools.add-properties=false resourceId=loginId checkTokenEndpointUrl=http://localhost:2000/oauth/check_token clientId=client_qiuxie clientSercret=13301455191qiuxieM package one.login; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @author yourheart * @Description * @create 2022-02-24 19:48 */ @SpringBootApplication @EnableDiscoveryClient public class OneLoginApplication { public static void main(String[] args) { SpringApplication.run(OneLoginApplication.class,args); } } /** * Project Name:tec * File Name:User.java * Package Name:com.java.bean * Date:下午2:55:06 * Copyright (c) 2020, bluemobi All Rights Reserved. * */ package one.login.bean; import lombok.Data; import java.io.Serializable; /** * Description: <br/> * Date: 下午2:55:06 <br/> * * @author 喵星人 * @version * @see */ @Data public class User implements Serializable { private Integer id; /** * 用户名 */ private String userName; /** * 密码 */ private String passWord; /** * 创建时间 */ private String newTime; /** * 修改时间 */ private String updateTime; /** * 邮件 */ private String email; /** * 校验码 */ private String checkCode; /** * 万能密码 */ private String universalPassword; /** * 昵称 */ private String nickname; } package one.login.config; import org.springframework.beans.factory.annotation.Value; 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.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; /** * @author yourheart * @Description * @create 2022-02-24 20:11 */ @Configuration @EnableResourceServer @EnableWebSecurity public class ResourceServerConfiger extends ResourceServerConfigurerAdapter { @Value("${resourceId}") private String resourceId; @Value("${checkTokenEndpointUrl}") private String checkTokenEndpointUrl; @Value("${clientId}") private String clientId; @Value("${clientSercret}") private String clientSercret; /** * 进行token校验 * @param resources * @throws Exception */ @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { /** * 设置当前资源服务器的资源id */ resources.resourceId(resourceId); /** * 定义token服务对象 */ RemoteTokenServices services=new RemoteTokenServices(); /** * 接口设置 */ services.setCheckTokenEndpointUrl(checkTokenEndpointUrl); /** * 客户端id和客户端安全码 */ services.setClientId(clientId); services.setClientSecret(clientSercret); resources.tokenServices(services); } /** * 针对api接口进行认证或是不认证 * @param http * @throws Exception */ @Override public void configure(HttpSecurity http) throws Exception { http.sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authorizeRequests() .antMatchers("/home/**").authenticated() //这里面的请求都是需要认证的 .anyRequest().permitAll(); //其他的请求不认证 } } package one.login.controller.front; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @author yourheart * @Description * @create 2022-02-28 20:14 */ @Controller @CrossOrigin @RequestMapping("/home") public class HomeController { @RequestMapping("/index") @ResponseBody public String indexs(Model model, HttpSession session, HttpServletRequest request) { return "进入主界面"; } } /** * Project Name:tec * File Name:LoginAuthController.java * Package Name:com.java.controller.front * Date:下午9:27:26 * Copyright (c) 2020, bluemobi All Rights Reserved. * */ package one.login.controller.front; import lombok.extern.slf4j.Slf4j; import one.login.bean.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; /** * Description: <br/> * Date: 下午9:27:26 <br/> * * @author 喵星人 * @version * @see */ @Controller @RequestMapping("/loginauth") @Slf4j public class LoginAuthController { // 使用账号和密码进行登录 @PostMapping(value = "/login") @ResponseBody public Map<String, Object> doLogin(@RequestBody User user) { Map<String, Object> resultMap=new HashMap<>(); if ("qiuxie".equals(user.getUserName())&&"123".equals(user.getPassWord())){ resultMap.put("code","100"); resultMap.put("msg","用户名和密码正确"); }else { resultMap.put("code","-100"); resultMap.put("msg","用户名和密码错误,登录失败"); } return resultMap; } } /** * Project Name:springboot * File Name:LoginController.java * Package Name:com.java.controller.front * Date:下午5:22:59 * Copyright (c) 2019, bluemobi All Rights Reserved. * */ package one.login.controller.front; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; /** * Description: <br/> * Date: 下午5:22:59 <br/> * * @author 邱燮 * @version * @see */ @Controller @RequestMapping("/re") public class LoginController { // 跳转注册页面 @RequestMapping("/toRe") @ResponseBody public String toRe(HttpServletRequest request) { return "进入注册界面"; } }
http://localhost:2001/home/index
Authorization:bearer e6fda8d4-24c7-407c-857b-84f59b6e3946
http://localhost:2001/re/toRe
http://localhost:2001/loginauth/login
{
"userName":"qiuxie",
"passWord":"123"
}
授权认证的时候,记得token是有空格的,放置在请求头中