All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yanyun.auth.config.AuthResourceAutoConfiguration Maven / Gradle / Ivy

There is a newer version: 1.5.0
Show newest version
package com.yanyun.auth.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yanyun.auth.dto.ResultDto;
import com.yanyun.auth.exception.TokenLegalException;
import com.yanyun.auth.service.AuthSystemService;
import com.yanyun.auth.service.AuthUserService;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
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.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties(AuthProperties.class)
@Import(AuthAnnotationConfiguration.class)
public class AuthResourceAutoConfiguration {
    /**
     * 注入配置类
     */
    @Autowired
    private AuthProperties authProperties;

    /**
     * 注入JWT编解码类,并设置密钥
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(authProperties.getSigningKey());
        return jwtAccessTokenConverter;
    }
    /**
     * 设置token 由JWT产生
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public JwtTokenStore jwtTokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    /**
     * 注入调用接口
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }


    /**
     * 注入系统操作组件
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public AuthSystemService authSystemService(){
        return new AuthSystemService(restTemplate(),authProperties.getAuthUrl());
    }

    /**
     * 注入用户操作组件
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public AuthUserService authUserService(){
        return new AuthUserService(restTemplate(),authProperties.getClientId(),authProperties.getClientSecret(),authProperties.getAuthUrl());
    }

    /**
     * 提供默认的资源拦截器配置,默认为不开启,
     * 开启的话需要在配置文件中: authentication.enable=true   来开启使用
     */
    @Configuration
    @EnableResourceServer
    @ConditionalOnProperty(prefix = "authentication",name = "enable",matchIfMissing = false)
    class CustomAuthConfigruation extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.tokenStore(jwtTokenStore())
                    //权限不足时会调用
                    .accessDeniedHandler((request, response, accessDeniedException) -> {
                        response.setContentType("application/json;charset=utf-8");
                        ObjectMapper om = new ObjectMapper();
                        Map map = new HashMap();
                        map.put("code", "403");
                        map.put("path", request.getRequestURI());
                        map.put("msg", "无权限,请与管理员联系");
                        om.writeValue(response.getOutputStream(), map);
                    })

                    //token失效时会调用
                    .authenticationEntryPoint((request, response, authException) -> {
                        response.setContentType("application/json;charset=utf-8");
                        ObjectMapper om = new ObjectMapper();
                        Map map = new HashMap();
                        map.put("path", request.getRequestURI());
                        if(authException.getCause() instanceof InvalidTokenException){
                            map.put("code", "403");
                            map.put("msg", "token无效,请确定token是否正确");
                        }else {
                            map.put("code", "401");
                            map.put("msg","需要认证才可以访问");
                        }
                        om.writeValue(response.getOutputStream(), map);
                    });
        }

        /**
         * 默认关闭csrf
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy