- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经设法用 spring mvc 创建了 REST API。我的目的是用 JWToken 保护资源。
现在我正在尝试编写三个测试:
1. 获取授权用户/密码的Token Authentication Fail => test:OK
2. 获取未授予用户/密码的Token Authentication success => test:OK
3.获取 protected 资源,不提供Token => test:fail 因为我的rest服务给了 protected 资源....
这是我的 REST Controller :
@Component
@RestController
@RequestMapping(value="/protected")
public class HelloWorldRest {
/**
* Logger
*/
private static final Logger LOG = LoggerFactory
.getLogger(HelloWorldRest.class);
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
/**
* permet de générer un token
*
* @param idFonc
*/
@RequestMapping(value="/greeting/{name}")
public Greeting greeting(@PathVariable String name) {
LOG.info("Fonction greeting : "+name);
return new Greeting(counter.incrementAndGet(),
String.format(template, name+ ", je suis Mister Toto"));
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "/tokenEndPointsTests.xml" })
public class tokenEndPointsTests {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Autowired
private Filter resourceServerFilter;
@Before
public void setup() {
// mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilter(resourceServerFilter,"/protected").build();
}
@Test
public void testgetToken() throws Exception {
UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken(
new Principal() {
@Override
public String getName() {
return "user";
}
}, null, null);
MvcResult mvcresult = mockMvc
.perform(
get("/oauth/token").param("client_id", "user")
.param("client_secret", "password")
.param("grant_type", "password")
.param("username", "user")
.param("password", "password")
.principal(principal)).andDo(print())
.andExpect(status().isOk()).andReturn();
MockHttpServletRequest mockhttp = mvcresult.getRequest();
System.out.println(mockhttp.toString());
}
@Test
public void testgetTokenEchec() throws Exception {
UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken(
new Principal() {
@Override
public String getName() {
// c'est le nom de l'user ...
return "user1";
}
}, null, null);
MvcResult mvcresult = mockMvc
.perform(
get("/oauth/token").param("client_id", "user")
.param("client_secret", "password")
.param("grant_type", "password")
.param("username", "user")
.param("password", "password")
.principal(principal)).andDo(print())
.andExpect(status().isUnauthorized()).andReturn();
MockHttpServletRequest mockhttp = mvcresult.getRequest();
System.out.println(mockhttp.toString());
}
@Test
public void testgetProtectedResource() throws Exception {
MvcResult mvcresult = mockMvc.perform(get("/protected/greeting/toto"))
.andDo(print()).andExpect(status().isUnauthorized())
.andReturn();
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xmlns:sec="http://www.springframework.org/schema/security" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sample" />
<mvc:annotation-driven />
<mvc:annotation-driven />
<sec:http pattern="/oauth/token" create-session="stateless"
authentication-manager-ref="authenticationManager">
<sec:intercept-url pattern="/oauth/token" />
<sec:http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<sec:custom-filter ref="clientCredentialsTokenEndpointFilter"
before="BASIC_AUTH_FILTER" />
<sec:access-denied-handler ref="oauthAccessDeniedHandler" />
</sec:http>
<sec:http pattern="/protected/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint">
<sec:anonymous enabled="false" />
<sec:intercept-url pattern="/protected/**" />
<sec:custom-filter ref="resourceServerFilter"
before="PRE_AUTH_FILTER" />
<sec:access-denied-handler ref="oauthAccessDeniedHandler" />
</sec:http>
<bean id="oauthAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
</bean>
<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="springsec/client" />
<property name="typeName" value="Basic" />
</bean>
<bean id="oauthAccessDeniedHandler"
class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler">
</bean>
<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="authenticationManager" />
</bean>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider
user-service-ref="clientDetailsUserService">
</sec:authentication-provider>
</sec:authentication-manager>
<bean id="clientDetailsUserService"
class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<bean id="clientDetails"
class="com.sample.context.security.InMemoryClientDetailsServiceSample">
</bean>
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices">
<oauth:password authentication-manager-ref="authenticationManager" />
</oauth:authorization-server>
<oauth:resource-server id="resourceServerFilter"
token-services-ref="tokenServices" />
<bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.store.JwtTokenStore">
<constructor-arg ref="JwttokenConverter"></constructor-arg>
</bean>
<bean id="JwttokenConverter"
class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter" />
<bean id="tokenServices" class="com.sample.context.security.JWTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="false" />
<property name="accessTokenValiditySeconds" value="3600"></property>
<property name="clientDetailsService" ref="clientDetails" />
<property name="accessTokenEnhancer" ref="JwttokenConverter"></property>
</bean>
</beans>
最佳答案
似乎有一些问题对我来说很明显。
使用 springSecurityFilterChain
您应该使用包含授权规则的 springSecurityFilterChain,而不是使用 resourceServerFilter。
将安全过滤器映射到 "/**"
MockMvc 的过滤器的映射只映射到/protected,但它应该映射到每个 URL。在内部 Spring Security 只会调用必要的过滤器。
可以在下面找到这两个更改的摘要:
MockMvc mockMvc;
// use springSecurityFilterChain
@Autowired
private Filter springSecurityFilterChain;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
// Use springSecurityFilterChain & remove "/protected"
.addFilter(springSecurityFilterChain)
.build();
}
<sec:http pattern="/protected/**" create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint">
<sec:anonymous enabled="false" />
<!-- Ensure you define an access attribute below! -->
<sec:intercept-url pattern="/protected/**" access="ROLE_USER"/>
<sec:custom-filter ref="resourceServerFilter"
before="PRE_AUTH_FILTER" />
<sec:access-denied-handler ref="oauthAccessDeniedHandler" />
</sec:http>
关于Spring MockMvcBuilders 安全过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28281272/
我已经设法用 spring mvc 创建了 REST API。我的目的是用 JWToken 保护资源。 现在我正在尝试编写三个测试: 1. 获取授权用户/密码的Token Authentication
我是 looking at the documentation here , 所有的例子都使用 MockMvcBuilders.webAppContextSetup 我尝试了这些例子 MockMvcB
我正在开发一个 Spring MVC 3.2 Web 应用程序,我正在尝试使用新的 MockMvc在我的单元测试中测试实用程序。我想测试单个 Controller 和整个 Web 应用程序加载我的 S
我正在这样创建我的 Controller 和 Controller 建议: 测试类: @RunWith(SpringRunner.class) @SpringBootTest public class
我正在使用 Spring Boot 1.2.5-RELEASE。我有一个接收 MultipartFile 和 String 的 Controller @RestController @RequestM
下面的测试(我包括了两个类以查看其中一个是否可以工作)都没有调用 Controller 的问题。我希望它因 CORS 问题而被拒绝,因为我没有添加任何 CORS 配置。 (然后我想使用 CORS 配置
我是一名优秀的程序员,十分优秀!