spring安全令牌请求需要身份验证

时间:2017-04-03 13:24:49

标签: spring security authentication oauth-2.0

我正在尝试实施OAuth 2.0的授权代码授权流程。但是在令牌请求上遇到了身份验证弹出问题。

这是我的代码。

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

@Configuration 公共类SecurityConfig        扩展WebSecurityConfigurerAdapter {

@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("admin").password("abc").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and().csrf().disable();
}

}

@Configuration
@EnableAuthorizationServer
public class AuthServerOAuth2Config 
        extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("test")
                .secret("test_secret")
                .authorizedGrantTypes("authorization_code")
                .scopes("write");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints
                .authorizationCodeServices(authorizationCodeServices())
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore())
                .approvalStoreDisabled();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    protected AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }
}

要获取令牌,请执行以下步骤:

  1. 使用浏览器转到: http://localhost:9000/oauth/authorize?response_type=code&client_id=test&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=write

  2. 首先,它将我重定向到一个登录表单,我在其中输入用户名和密码:admin abc

  3. 然后询问我是否允许向我的“测试”客户提供许可。
  4. 它将我重定向到“redirect uri”:http://localhost:8080?code=XXX
  5. 然后我复制代码并使用Google Advanced Rest Client发送令牌请求: 发布在http://localhost:9000/oauth/token?client_id=test&grant_type=authorization_code&code=XXX上 没有任何标题。据我所知,海报应该使用浏览器cookie。
  6. 作为令牌请求的结果,我看到一个弹出窗口,要求填写用户名和密码,同时期望获得访问令牌作为响应。
  7. Poster popup

    请帮我解决问题。我应该在令牌请求中添加一些标头吗?或者我的授权服务器配置不正确?

1 个答案:

答案 0 :(得分:1)

我自己只是在阅读OAuth2规范的其他资源时找到了问题的原因。 它需要在令牌请求上发送具有以下值的授权:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import matplotlib.gridspec as gridspec
from matplotlib.patches import ConnectionPatch
import matplotlib.animation
plt.rcParams["figure.figsize"] = np.array([6,3.6])*0.7

x = np.linspace(-3,3)
X,Y = np.meshgrid(x,x)
f = lambda x,y: (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)+1.5
Z = f(X,Y)

bins=np.linspace(Z.min(), Z.max(), 16)
cols = plt.cm.PuOr((bins[:-1]-Z.min())/(Z.max()-Z.min()))

gs = gridspec.GridSpec(2, 2, height_ratios=[34,53], width_ratios=[102,53])
fig = plt.figure()
ax=fig.add_subplot(gs[:,0])
ax2=fig.add_subplot(gs[0,1])
ax3=fig.add_subplot(gs[1,1])

ax.imshow(Z, cmap="PuOr")
rec = plt.Rectangle([-.5,-.5], width=9, height=9, edgecolor="crimson", fill=False, lw=2)
conp = ConnectionPatch(xyA=[-0.5,0.5], xyB=[9.5,4], coordsA="data", coordsB="data",
                      axesA=ax3, axesB=ax, arrowstyle="-|>", zorder=25, shrinkA=0, shrinkB=1,
                      mutation_scale=20, fc="w", ec="crimson", lw=2)
ax3.add_artist(conp)
ax.add_artist(rec)
im = ax3.imshow(Z[:9,:9], cmap="PuOr", vmin=Z.min(), vmax=Z.max())
ticks = np.array([0,4,8])
ax3.set_yticks(ticks); ax3.set_xticks(ticks)
ax2.hist(Z[:9,:9].flatten(), bins=bins)

def ins(px,py):
    global rec, conp, histpatches
    ll = [px-.5,py-.5]
    rec.set_xy(ll)
    conp.remove()
    conp = ConnectionPatch(xyA=[-0.5,0.5], xyB=[px+9.5,py+4], coordsA="data", coordsB="data",
                      axesA=ax3, axesB=ax, arrowstyle="-|>", zorder=25, shrinkA=0, shrinkB=1,
                      mutation_scale=20, fc="w", ec="crimson", lw=2)
    ax3.add_patch(conp)
    data = Z[px:px+9,py:py+9]
    im.set_data(data)
    ax3.set_xticklabels(ticks+px)
    ax3.set_yticklabels(ticks+py)
    ax2.clear()
    ax2.set_ylim(0,60)
    h, b_, patches = ax2.hist(data.flatten(), bins=bins, ec="k", fc="#f1a142")
    [pat.set_color(cols[i]) for i, pat in enumerate(patches)]

def func(p):
    px,py = p
    ins(px, py)

phi = np.linspace(0.,2*np.pi)
r = np.sin(2*phi)*20+np.pi/2
xr = (r*np.cos(phi)).astype(np.int8)
yr = (r*np.sin(phi)).astype(np.int8)

plt.subplots_adjust(top=0.93,bottom=0.11,left=0.04,right=0.96,hspace=0.26,wspace=0.15)
frames = np.c_[xr+20, yr+20]
ani = matplotlib.animation.FuncAnimation(fig, func, frames=frames, interval=300, repeat=True)

plt.show()