@Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient(ClientID) .secret(passwordEncoder.encode(ClientSecret)) .authorizedGrantTypes("authorization_code", "refresh_token", "password", "implicit") .scopes("read","write","del","userinfo") .redirectUris(RedirectURLs); }
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();//支持把secret和clientid寫在url上,不然須要在頭上
}
Authorization Ccode------RFRLFY access_token_url http://localhost:8081/oauth/token?client_id=android1&code=RFRLFY&grant_type=authorization_code&redirect_uri=http://localhost:8081/callback&client_secret=android1 Access Token Response ---------{"access_token":"faadf3bf-6488-4036-bc3b-21b0a979602c","token_type":"bearer","refresh_token":"1b01f133-c5ab-419f-8125-088c85916ecb","expires_in":43187,"scope":"read"}
回調頁面代碼,主要實現了對code的獲取,對access_token的組織,而後請求時把access_token帶上,這個方法通常會作成公用的過濾器node
@Controller public class UserController { @RequestMapping(value = "/callback", method = RequestMethod.GET) public ResponseEntity<String> callback(@RequestParam("code") String code) throws JsonProcessingException, IOException { ResponseEntity<String> response = null; System.out.println("Authorization Ccode------" + code); RestTemplate restTemplate = new RestTemplate(); String access_token_url = "http://localhost:8081/oauth/token"; access_token_url += "?client_id=android1&code=" + code; access_token_url += "&grant_type=authorization_code"; access_token_url += "&redirect_uri=http://localhost:8081/callback"; access_token_url += "&client_secret=android1"; System.out.println("access_token_url " + access_token_url); response = restTemplate.exchange(access_token_url, HttpMethod.POST, null, String.class); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response.getBody()); String token = node.path("access_token").asText(); System.out.println("access_token" +access_token);
String url = "http://localhost:8081/index"; HttpHeaders headers1 = new HttpHeaders(); headers1.add("Authorization", "Bearer " + token); HttpEntity<String> entity = new HttpEntity<>(headers1); ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); return result; }
@Configuration @EnableResourceServer @Order(6) public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable()//禁用了 csrf 功能 .authorizeRequests()//限定簽名成功的請求 .antMatchers("/index").access("#oauth2.hasScope('del')") //受權碼scopes裏須要選中del才能夠訪問 .antMatchers("/user").authenticated()//簽名成功後可訪問,不受role限制 .anyRequest().permitAll()//其餘沒有限定的請求,容許訪問 .and().anonymous()//對於沒有配置權限的其餘請求容許匿名訪問 .and().formLogin()//使用 spring security 默認登陸頁面 .and().httpBasic();//啓用http 基礎驗證 } }
若是你對用戶進行了角色和權限的配置,對於某些保護接口須要有指定權限才能訪問的話,須要重getAuthorities方法,不然,你的權限將會失效!android
@Entity @Data public class User extends BaseEntity implements UserDetails { @Id @GeneratedValue private Long id; private String username; private String password; private String firstName; private String lastName; @Email private String email; private String imageUrl; @JsonIgnore @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER) @BatchSize(size = 20) private Set<Role> roles = new HashSet<>(); @Transient private Set<GrantedAuthority> authorities = new HashSet<>(); /** * 注意,這塊須要加@Override重寫,不然權限無效. * * @return */ @Override public Set<GrantedAuthority> getAuthorities() { Set<GrantedAuthority> authorities = new HashSet<>(); for (Role role : this.roles) { for (Authority authority : role.getAuthorities()) { authorities.add(new SimpleGrantedAuthority(authority.getValue())); } } return authorities; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
感謝閱讀!spring