天天看点

spring security oauth2 微博 授权登录

spring security oauth2 微博 授权登录

官网:https://open.weibo.com/wiki/授权机制

**********************

示例

***************

配置文件

application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          weibo:
            provider: weibo
            client-id: ******
            client-secret: ******
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/weibo"
            scope: follow_app_official_microblog
        provider:
          weibo:
            authorization-uri: https://api.weibo.com/oauth2/authorize
            token-uri: https://api.weibo.com/oauth2/access_token
            user-info-uri: https://api.weibo.com/2/users/show.json
           

***************

oauth2/weibo 

WeiboOAuth2User

public class WeiboOAuth2User implements OAuth2User {

    private String id;
    private String name;
    private String province;

    private List<GrantedAuthority> authorities= AuthorityUtils.createAuthorityList("ROLE_USER");
    private Map<String,Object> attributes;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public Map<String, Object> getAttributes() {
        if (attributes==null){
            attributes=new HashMap<>();

            attributes.put("id",this.getId());
            attributes.put("name",this.getName());
            attributes.put("province",this.getProvince());
        }

        return attributes;
    }
}
           

WeiboOAuth2AccessTokenResponseClient:获取access_token

@Component
public class WeiboOAuth2AccessTokenResponseClient implements OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest oAuth2AuthorizationCodeGrantRequest) {
        ClientRegistration clientRegistration=oAuth2AuthorizationCodeGrantRequest.getClientRegistration();

        System.out.println("registerId:"+clientRegistration.getRegistrationId());
        OAuth2AuthorizationExchange oAuth2AuthorizationExchange=oAuth2AuthorizationCodeGrantRequest.getAuthorizationExchange();

        Map<String,String> params=new HashMap<>();
        params.put("client_id",clientRegistration.getClientId());
        params.put("client_secret",clientRegistration.getClientSecret());
        params.put("grant_type",clientRegistration.getAuthorizationGrantType().getValue());
        params.put("code",oAuth2AuthorizationExchange.getAuthorizationResponse().getCode());
        params.put("redirect_uri",oAuth2AuthorizationExchange.getAuthorizationResponse().getRedirectUri());
        System.out.println(params);

        String baseUri=clientRegistration.getProviderDetails().getTokenUri();

        String accessTokenUri=baseUri+ "?client_id={client_id}"+
                "&client_secret={client_secret}"+
                "&grant_type={grant_type}"+
                "&redirect_uri={redirect_uri}"+
                "&code={code}";

        String accessTokenResponse=restTemplate.postForObject(accessTokenUri,null,String.class,params);

        JSONObject object=JSONObject.parseObject(accessTokenResponse);
        String accessToken=object.getString("access_token");
        String expires_in=object.getString("expires_in");
        String uid=object.getString("uid");

        Map<String,Object> additionalParameters=new HashMap<>();
        additionalParameters.put("uid",uid);

        return OAuth2AccessTokenResponse.withToken(accessToken)
                .expiresIn(Long.parseLong(expires_in))
                .tokenType(OAuth2AccessToken.TokenType.BEARER)
                .scopes(oAuth2AuthorizationExchange.getAuthorizationRequest().getScopes())
                .additionalParameters(additionalParameters)
                .build();
    }
}
           

WeiboOAuth2UserService:加载用户信息

@Component
public class WeiboOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException {
        Map<String,Object> additionalParameters=oAuth2UserRequest.getAdditionalParameters();
        String uid=additionalParameters.get("uid").toString();

        String access_token=oAuth2UserRequest.getAccessToken().getTokenValue();

        Map<String,String> params=new HashMap<>();
        params.put("uid",uid);
        params.put("access_token",access_token);

        String baseUri=oAuth2UserRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();
        String userInfoUri=baseUri+"?uid={uid}"+"&access_token={access_token}";
        System.out.println(userInfoUri);

        return restTemplate.getForObject(userInfoUri,WeiboOAuth2User.class,params);
    }
}
           

***************

config 层

WebSecuriyConfig

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserService userService;

    @Resource
    private WeiboOAuth2AccessTokenResponseClient weiboOAuth2AccessTokenResponseClient;

    @Resource
    private WeiboOAuth2UserService weiboOAuth2UserService;

    @Bean
    public PasswordEncoder initPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login/gitee").loginProcessingUrl("/login/form")
                .and()
                .authorizeRequests()
                .antMatchers("/hello").hasAnyAuthority("ROLE_USER")
                .antMatchers("/**").permitAll()
                .and()
                .logout().deleteCookies("JSESSIONID")
                .logoutSuccessUrl("/").permitAll();

        http.oauth2Login().loginPage("/login/gitee")
                .tokenEndpoint().accessTokenResponseClient(weiboOAuth2AccessTokenResponseClient)
                .and()
                .userInfoEndpoint()
                .userService(weiboOAuth2UserService);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(initPasswordEncoder());
    }
}
           

***************

controller 层

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Principal principal){
        System.out.println(principal.toString());

        return "hello "+principal.getName();
    }

    @RequestMapping("/")
    public String redirect(){
        return "redirect";
    }
}           

***************

前端页面

login.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/login/form}" th:align="center" method="post">
    username:<input th:type="text" name="username"><br>
    password:<input th:type="text" name="password"><br>
    <button>提交</button>
</form>

<div th:align="center">
    <a th:href="@{/oauth2/authorization/weibo}" target="_blank" rel="external nofollow" >weibo</a><br>
</div>
</body>
</html>           

**********************

使用测试

127.0.0.1:8080/hello

spring security oauth2 微博 授权登录

授权认证通过后,输出:hello o_小李子_o

继续阅读