美文网首页Oauth2SpringBootJava学习
spring boot oauth2单点登录(一):前后端分离例

spring boot oauth2单点登录(一):前后端分离例

作者: 樱花舞 | 来源:发表于2021-10-10 10:31 被阅读0次

    相关文章

    1、spring boot oauth2单点登录(一)-前后端分离例子
    2、spring boot oauth2单点登录(二)-客户端信息存储
    3、spring boot oauth2单点登录(三)-token存储方式
    4、spring boot oauth2单点登录(四)-code存储方式

    源码地址

    后端:https://gitee.com/fengchangxin/sso
    前端:https://gitee.com/fengchangxin/sso-page

    准备

    后端:三个spring boot应用,auth(授权管理),client1(客户端应用1),client2(客户端应用2)。
    前端:三个Vue项目,auth,client1,client2。分别对应三个后端应用。
    工具:nginx
    域名:oauth.com,client1.com,client2.com,分别对应三个系统。
    开发环境:先在host文件添加上面三个域名。
    端口:
    后端服务auth(8080),client1(8081),client2(8082)。
    前端auth(8083),client1(8084),client2(8085)。
    依赖:

    <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    

    测试地址:
    client1:http://client1.com/client1Page/#/home
    client2:http://client2.com/client2Page/#/home
    登录用户:admin/123456

    备注:此篇文章对应的授权中心:auth
    此篇文章是开发环境下的,nginx配置生产环境有所不同,请注意。文章中列出的只是一些关键地方,一些细节还是要看整个项目代码。

    配置nginx

    都是监听80端口和三个域名,例如client1,/client1/转到后端服务,/clientPage/转到Vue前端服务,同时要配置~ .*.(js|css)$,一些js和css文件转到前端服务地址,不然无法访问到本地Vue服务。至于为什么要用nginx,那是要把前端和后端的地址都是同域名下,解决跨域问题。

        server {
        listen       80;
        server_name  client1.com;
        location /client1/ {
            proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://localhost:8081/client1/;
        }
    
        location /client1Page/ {
            proxy_pass http://localhost:8084/;
        }
        location ~ .*\.(js|css)$ {
            proxy_pass http://localhost:8084;
        }
        }
    
        server {
        listen       80;
        server_name  client2.com;
        location /client2/ {
            proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_pass http://localhost:8082/client2/;
        }
        location /client2Page/ {
            proxy_pass http://localhost:8085/;
        }
    
        location ~ .*\.(js|css)$ {
            proxy_pass http://localhost:8085;
        }
        }
    
        server {
            listen       80;
            server_name  oauth.com;
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
        location /auth/ {
            proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://localhost:8080/auth/;
        }
        location /authPage/ {
            proxy_pass http://localhost:8083/;
        }
    
        location ~ .*\.(js|css)$ {
            proxy_pass http://localhost:8083;
        }
        }
    

    一、授权管理系统

    1、后端授权管理服务

    1.1自定义登录成功、登录失败、未登录的返回处理

    未登录处理
    在这里做了两个逻辑处理,根据参数isRedirect是否是true,如果是true则重定向到授权中心auth的前端登录页,若为空或false,则返回授权中心的后端授权接口,并带上isRedirect=true,定义Result对象的code为800则为未登录。

    @Component("unauthorizedEntryPoint")
    public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
            Map<String, String[]> paramMap = request.getParameterMap();
            StringBuilder param = new StringBuilder();
            paramMap.forEach((k, v) -> {
                param.append("&").append(k).append("=").append(v[0]);
            });
            param.deleteCharAt(0);
            String isRedirectValue = request.getParameter("isRedirect");
            if (!StringUtils.isEmpty(isRedirectValue) && Boolean.valueOf(isRedirectValue)) {
                response.sendRedirect("http://oauth.com/authPage/#/login?"+param.toString());
                return;
            }
            String authUrl = "http://oauth.com/auth/oauth/authorize?"+param.toString()+"&isRedirect=true";
            Result result = new Result();
            result.setCode(800);
            result.setData(authUrl);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            writer.print(mapper.writeValueAsString(result));
            writer.flush();
            writer.close();
        }
    }
    

    登录成功返回处理

    @Component("successAuthentication")
    public class SuccessAuthentication extends SavedRequestAwareAuthenticationSuccessHandler {
    
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            Result result = new Result();
            result.setCode(0);
            result.setMsg("成功");
            ObjectMapper mapper = new ObjectMapper();
            writer.println(mapper.writeValueAsString(result));
            writer.flush();
            writer.close();
        }
    }
    

    登录失败返回处理

    @Component("failureAuthentication")
    public class FailureAuthentication extends SimpleUrlAuthenticationFailureHandler {
    
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            Result result = new Result();
            result.setCode(1000);
            result.setMsg("登录失败");
            ObjectMapper mapper = new ObjectMapper();
            writer.println(mapper.writeValueAsString(result));
            writer.flush();
            writer.close();
        }
    }
    

    1.2登录配置

    在内存添加两个登录用户,正式使用是存储在数据库,后续文章再写。同时把1.1的实现添加到此处。

    @EnableWebSecurity
    @Configuration
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Autowired
        private SuccessAuthentication successAuthentication;
        @Autowired
        private FailureAuthentication failureAuthentication;
        @Autowired
        private UnauthorizedEntryPoint unauthorizedEntryPoint;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsServiceBean()).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.cors().and().csrf().disable()
                    .exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint)
                    .and()
                    .authorizeRequests()
                    .antMatchers("/login").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().successHandler(successAuthentication).failureHandler(failureAuthentication);
        }
    
        @Bean
        @Override
        public UserDetailsService userDetailsServiceBean() {
            Collection<UserDetails> users = buildUsers();
    
            return new InMemoryUserDetailsManager(users);
        }
    
        private Collection<UserDetails> buildUsers() {
            String password = passwordEncoder().encode("123456");
    
            List<UserDetails> users = new ArrayList<>();
    
            UserDetails user_admin = User.withUsername("admin").password(password).authorities("ADMIN", "USER").build();
            UserDetails user_user1 = User.withUsername("user1").password(password).authorities("USER").build();
    
            users.add(user_admin);
            users.add(user_user1);
    
            return users;
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
    }
    

    1.3客户端应用信息配置

    在内存添加client1和client2客户端信息,正式使用是存储在数据库,后续文章再写。注意checkTokenAccess(),tokenKeyAccess()要配置,不然无法启动客户端应用,报401,403之类的错误。

    @EnableAuthorizationServer
    @Configuration
    public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
        @Autowired
        private PasswordEncoder passwordEncoder;
        
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.allowFormAuthenticationForClients()
                    .checkTokenAccess("isAuthenticated()")
                    .tokenKeyAccess("isAuthenticated()");
        }
    
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.withClientDetails(inMemoryClientDetailsService());
        }
    
    
        @Bean
        public ClientDetailsService inMemoryClientDetailsService() throws Exception {
            return new InMemoryClientDetailsServiceBuilder()
                    .withClient("client1")
                    .secret(passwordEncoder.encode("client1_secret"))
                    .scopes("all")
                    .authorizedGrantTypes("authorization_code", "refresh_token")
                    .redirectUris("http://client1.com/client1/login")
                    .accessTokenValiditySeconds(7200)
                    .autoApprove(true)
    
                    .and()
                    .withClient("client2")
                    .secret(passwordEncoder.encode("client2_secret"))
                    .scopes("all")
                    .authorizedGrantTypes("authorization_code", "refresh_token")
                    .redirectUris("http://client2.com/client2/login")
                    .accessTokenValiditySeconds(7200)
                    .autoApprove(true)
    
                    .and()
                    .build();
        }
    
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            super.configure(endpoints);
        }
    }
    

    1.4添加跨域

    这里允许了所有的域访问,可以根据客户端应用的域名来做限制,通过数据库、缓存等方式来存储允许访问的域。

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Configuration
    public class CORSFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            HttpServletRequest request = (HttpServletRequest) req;
            //允许所有的域访问,可以设置只允许自己的域访问
            response.setHeader("Access-Control-Allow-Origin", "*");
            //允许所有方式的请求
            response.setHeader("Access-Control-Allow-Methods", "*");
            //头信息缓存有效时长(如果不设 Chromium 同时规定了一个默认值 5 秒),没有缓存将已OPTIONS进行预请求
            response.setHeader("Access-Control-Max-Age", "3600");
            //允许的头信息
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
    
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                chain.doFilter(req, res);
            }
        }
    }
    

    二、后端客户端服务

    2.1登录配置

    配置所有接口都需要登录才能访问,同时用@EnableOAuth2Sso注解标注为客户端。

    @EnableOAuth2Sso
    @Configuration
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            super.configure(web);
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.logout()
                    .and()
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .csrf().disable();
        }
    }
    

    2.2 yml配置文件

    server:
      port: 8081
      servlet:
        context-path: /client1
    
    security:
      oauth2:
        client:
          client-id: client1
          preEstablishedRedirectUri:
          client-secret: client1_secret
          access-token-uri: http://oauth.com/auth/oauth/token
          user-authorization-uri: http://oauth.com/auth/oauth/authorize
        resource:
          user-info-uri: http://oauth.com/auth/user
          token-info-uri: http://oauth.com/auth/oauth/check_token
    

    2.3 回调接口

    客户端要实现一个根路径回调接口,一般正常流程的回调地址是开始请求的接口地址,但为什么是请求到根路径我也还没找到原因,所以这里就实现根路径接口,重定向到前端地址。

        @GetMapping("/")
        public void callback(HttpServletResponse response) throws IOException {
            response.sendRedirect("http://client1.com/client1Page/#/home");
        }
    

    三、前端应用

    具体请看码云代码。

    3.1 客户端前端

    主要是一个按钮,发起请求后端服务。当未登录时请求会返回800的错误,则跳转到授权中心的授权接口,注意要用window.location.href 开新标签页跳转,跳转地址为UnauthorizedEntryPoint返回的地址。

    3.2 授权管理前端

    主要是一个登录页,当客户端未登录时跳转到授权接口,授权中心判断未登录则跳转到此登录页。注意登录成功之后页面重新跳转时也要用window.location.href 重新跳转到授权接口。

    四、测试

    先启动nginx,然后在开发工具分别启动所有项目,比如idea、webstore,在浏览器中访问http://client1.com/client1Page/#/homehttp://client2.com/client2Page/#/home
    注意在登录成功之后返回页面并没有显示变化,并不是出问题,再次点击按钮即可查询到数据。

    相关文章

      网友评论

        本文标题:spring boot oauth2单点登录(一):前后端分离例

        本文链接:https://www.haomeiwen.com/subject/vnimnltx.html