소스 검색

登陆模块重构

chenweida 7 년 전
부모
커밋
34560743d7

+ 16 - 0
base/common-security/pom.xml

@ -19,6 +19,22 @@
            <groupId>org.springframework.cloud</groupId>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <artifactId>spring-boot-starter-data-redis</artifactId>

+ 47 - 0
base/common-security/src/main/java/com.yihu.base.security/AuthorizationServerConfig.java

@ -1,8 +1,23 @@
package com.yihu.base.security;
package com.yihu.base.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
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.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import javax.sql.DataSource;
/**
/**
 * Created by chenweida on 2017/12/4.
 * Created by chenweida on 2017/12/4.
@ -10,4 +25,36 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E
@Configuration
@Configuration
@EnableAuthorizationServer  //开启授权服务器
@EnableAuthorizationServer  //开启授权服务器
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(tokenStore());
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource).passwordEncoder(passwordEncoder).clients(clientDetailsService);
    }
    @Bean
    TokenStore tokenStore() {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        return redisTokenStore;
    }
}
}

+ 41 - 0
base/common-security/src/main/java/com.yihu.base.security/ResourceServerConfig.java

@ -1,8 +1,15 @@
package com.yihu.base.security;
package com.yihu.base.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
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.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/**
/**
 * Created by chenweida on 2017/12/4.
 * Created by chenweida on 2017/12/4.
@ -11,4 +18,38 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.R
@Configuration
@Configuration
@EnableResourceServer  //开启资源服务器
@EnableResourceServer  //开启资源服务器
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    protected AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    protected AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenStore redisTokenStore;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //这是账号密码登陆
        http.formLogin()//设置验证码 账号密码登陆
                .loginPage("/denglu.html")
                .loginProcessingUrl("/authentication/form")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/denglu.html",
                        "/authentication/form").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.
                authenticationManager(authenticationManager).
                tokenStore(redisTokenStore);
    }
}
}

+ 17 - 0
base/common-security/src/main/java/com.yihu.base.security/SercurityConfig.java

@ -0,0 +1,17 @@
package com.yihu.base.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
 * Created by chenweida on 2017/12/4.
 */
@Configuration
public class SercurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

+ 4 - 3
base/common-security/src/main/java/com.yihu.base.security/hander/BaseAuthenticationSuccessHandler.java

@ -16,6 +16,7 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Component;
@ -39,7 +40,7 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
    @Autowired
    @Autowired
    private ClientDetailsService clientDetailsService;
    private ClientDetailsService clientDetailsService;
    @Autowired
    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;
    private AuthorizationServerTokenServices defaultTokenServices;
    /*
    /*
     * (non-Javadoc)
     * (non-Javadoc)
@ -53,7 +54,7 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
                                        Authentication authentication) throws IOException, ServletException {
        String header = request.getHeader("Authorization");
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Basic ")) {
        if (org.springframework.util.StringUtils.isEmpty(header) ||(! header.startsWith("Basic "))) {
            throw new UnapprovedClientAuthenticationException("请求头没有client信息");
            throw new UnapprovedClientAuthenticationException("请求头没有client信息");
        }
        }
        //解析头部的basic信息
        //解析头部的basic信息
@ -77,7 +78,7 @@ public class BaseAuthenticationSuccessHandler extends SavedRequestAwareAuthentic
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        OAuth2AccessToken token = defaultTokenServices.createAccessToken(oAuth2Authentication);
        response.setContentType("application/json;charset=UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(token));
        response.getWriter().write(objectMapper.writeValueAsString(token));

+ 17 - 0
svr-lib-parent-pom/pom.xml

@ -51,6 +51,8 @@
        <version.jackson>2.8.1</version.jackson>
        <version.jackson>2.8.1</version.jackson>
        <version.myCommon>1.0.0</version.myCommon>
        <version.myCommon>1.0.0</version.myCommon>
        <version.spring>4.3.8.RELEASE</version.spring>
        <version.spring>4.3.8.RELEASE</version.spring>
        <version.spring.security>4.2.3.RELEASE</version.spring.security>
        <version.spring-data-jpa>1.11.3.RELEASE</version.spring-data-jpa>
        <version.spring-data-jpa>1.11.3.RELEASE</version.spring-data-jpa>
        <version.spring-data-common>1.13.3.RELEASE</version.spring-data-common>
        <version.spring-data-common>1.13.3.RELEASE</version.spring-data-common>
        <version.zipkin>1.24.0</version.zipkin>
        <version.zipkin>1.24.0</version.zipkin>
@ -361,6 +363,21 @@
                <version>${version.spring}</version>
                <version>${version.spring}</version>
            </dependency>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>${version.spring.security}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>${version.spring.security}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>${version.spring.security}</version>
            </dependency>
            <dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <artifactId>spring-context-support</artifactId>

+ 68 - 1
svr/svr-demo/readme.MD

@ -1 +1,68 @@
http://localhost:8080/oauth/authorize?client_id=cwd&redirect_uri=localhost:8080&scope=all
**授权码模式:(一直开放API用)**
获取code
http://localhost:8060/oauth/authorize?response_type=code&client_id=cwd&redirect_uri=http://example.com&scope=all
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"authorization_code",  
     "client_id":"cwd",
     "code":"第一步请求获取的code",
     "redirect_uri":"http://example.com",
     "scope":"all"
}
返回值
{
    "access_token":"bd677e24-2de5-4862-a5e1-8f90a074db42",
    "token_type":"bearer",
    "refresh_token":"1427b997-ef94-4061-8940-c71da6549acd",
    "expires_in":43199,
    "scope":"all"
}
**密码模式(一般自己公司系统用)**
获取token post请求
http://localhost:8060/oauth/token
header:  Basic {appid}:{appsecuri} 加密  例如 Basic Y3dkOmN3ZA==
  
{
     "grant_type":"password",  
     "username":"jojo",
     "password":"123456",
     "scope":"all"
}
返回值
{
    "access_token":"630e2ccc-a5ce-4486-a855-ba755eb3d0d2",
    "token_type":"bearer",
    "refresh_token":"bbb36b54-61b2-4d86-aed3-91c5135174c3",
    "expires_in":43199,
    "scope":"all"
}
**访问方式**
http://localhost:8060/user
header 
{
"Authorization":"bearer 630e2ccc-a5ce-4486-a855-ba755eb3d0d2"      即 bearer accesstoken
}
**自定义账号密码登陆**
POST
http://localhost:8060/authentication/form
header
Authorization  Basic Y3dkOmN3ZA==
body
{
    "username":"test",
    "password":"123456"
}
**自定义手机号短信验证码登陆**

+ 2 - 3
svr/svr-demo/src/main/java/com/yihu/jw/service/UserService.java

@ -1,7 +1,6 @@
package com.yihu.jw.service;
package com.yihu.jw.service;
import com.sun.javafx.scene.control.skin.VirtualFlow;
import com.yihu.jw.model.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetails;
@ -34,7 +33,7 @@ public class UserService implements UserDetailsService {
        if ("admin".equals(userName)) {
        if ("admin".equals(userName)) {
            System.out.printf("password:"+passwordEncoder.encode("123456"));
            System.out.printf("password:"+passwordEncoder.encode("123456"));
            return new User("admin",
            return new User("admin",
                    "123456",
                    passwordEncoder.encode("123456"),
                    true,
                    true,
                    true,
                    true,
                    true,
                    true,

+ 1 - 26
svr/svr-demo/src/main/resources/resources/denglu.html

@ -7,7 +7,7 @@
<body>
<body>
	<h2>标准登录页面</h2>
	<h2>标准登录页面</h2>
	<h3>表单登录</h3>
	<h3>表单登录</h3>
	<form action="/authentication/form" method="post">
<form action="/authentication/form" method="post">
		<table>
		<table>
			<tr>
			<tr>
				<td>用户名:</td> 
				<td>用户名:</td> 
@ -32,30 +32,5 @@
			</tr>
			</tr>
		</table>
		</table>
	</form>
	</form>
	
	<h3>短信登录</h3>
	<form action="/authentication/mobile" method="post">
		<table>
			<tr>
				<td>手机号:</td>
				<td><input type="text" name="mobile" value="13012345678"></td>
			</tr>
			<tr>
				<td>短信验证码:</td>
				<td>
					<input type="text" name="smsCode">
					<a href="/code/sms?mobile=13012345678">发送验证码</a>
				</td>
			</tr>
			<tr>
				<td colspan="2"><button type="submit">登录</button></td>
			</tr>
		</table>
	</form>
	<br>
	<h3>社交登录</h3>
	<a href="/qqLogin/callback.do">QQ登录</a>
	&nbsp;&nbsp;&nbsp;&nbsp;
	<a href="/qqLogin/weixin">微信登录</a>
</body>
</body>
</html>
</html>