Ich habe die folgenden Links zum Testen und Testen von OAuth2 @ PreAuthorise (hasAnyRole ('ADMIN', 'TEST') zum Beispiel, aber ich kann keine der Tests zu bestehen oder sogar authentifizieren.SpringSecurity WithSecurityContext MockMvc OAuth2 immer unbefugt
Wenn ich versuche, mit admin (oder einer Rolle) auf den Endpunkt zuzugreifen, wird es sich nie richtig authentifizieren.Fehlt etwas Offensichtliches, scheint es, dass ich alles genauso habe wie in den Beispielen.Ich habe auch eine andere Alternative ausprobiert an die WithSecurityContext Factory mit OAuth-spezifischer Authentifizierung und immer noch kein Glück.Alle Hilfe wäre willkommen.
https://stackoverflow.com/a/31679649/2594130 und http://docs.spring.io/spring-security/site/docs/4.0.x/reference/htmlsingle/#test
mein Controller Ich teste
@RestController
@RequestMapping("/bookmark/")
public class GroupBookmarkController {
@Autowired
BookmarkService bookmarkService;
/**
* Get list of all bookmarks
*/
@RequestMapping(value = "{groupId}", method = RequestMethod.GET)
@PreAuthorize("hasAnyRole(['ADMIN', 'USER'])")
public ResponseEntity<List<Bookmark>> listAllGroupBookmarks(@PathVariable("groupId") String groupId) throws BookmarkNotFoundException {
List<Bookmark> bookmarks = bookmarkService.findAllBookmarksByGroupId(groupId);
return new ResponseEntity<>(bookmarks, HttpStatus.OK);
}
...
}
My Test Klasse
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BookmarkServiceApplication.class)
@WebAppConfiguration
public class BookmarkServiceApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void loadData() {
this.mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.alwaysDo(print())
.build();
}
@Test
@WithMockCustomUser(username = "test")
public void getBookmarkAuthorised() throws Exception {
mockMvc.perform(get("/bookmark/nvjdbngkjlsdfngkjlfdsnlkgsd"))
.andExpect(status().is(HttpStatus.SC_OK));
// always 401 here
}
}
Mein BookmarkServiceApplication
@SpringBootApplication
@EnableResourceServer
public class BookmarkServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BookmarkServiceApplication.class, args);
}
}
Mein WithSecurityContextFactory
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockCustomUser> {
@Override
public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
UserDetails principal = new User(customUser.username(), "password", true, true, true, true, grantedAuthorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(
principal, principal.getPassword(), principal.getAuthorities());
context.setAuthentication(authentication);
return context;
}
}
Meine WithSecurityContext Annotation
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockCustomUser {
String username() default "user";
String name() default "Test User";
}
Per @RobWinch ‚Antwort
Hallo @RobWinch ich Sie Vorschlag mit der staatenlos Flagge versucht haben, half dies mit einem Teil der Antwort. Jedoch in Ihrer Antwort auf diese Frage [Frühling OAuth und Boot-Integration Test] (https://stackoverflow.com/a/31679649/2594130) erwähnen Sie
Sie müssen nicht mehr über das Laufen in stateless kümmern oder nicht
Warum es, dass ich ist muss noch das stateless false hinzufügen, ist das ein Bug oder verwenden wir es etwas anders?
Das andere, was ich dies zu tun zu erhalten benötigt wurde Zugabe OAuth2Request und OAuth2Authentication zum WithSecurityContextFactory, wie Sie in der folgenden
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockOAuthUser> {
@Override
public SecurityContext createSecurityContext(WithMockOAuthUser withClient) {
// Get the username
String username = withClient.username();
if (username == null) {
throw new IllegalArgumentException("Username cannot be null");
}
// Get the user roles
List<GrantedAuthority> authorities = new ArrayList<>();
for (String role : withClient.roles()) {
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role);
}
authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
// Get the client id
String clientId = withClient.clientId();
// get the oauth scopes
String[] scopes = withClient.scope();
Set<String> scopeCollection = Sets.newSet(scopes);
// Create the UsernamePasswordAuthenticationToken
User principal = new User(username, withClient.password(), true, true, true, true, authorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
principal.getAuthorities());
// Create the authorization request and OAuth2Authentication object
OAuth2Request authRequest = new OAuth2Request(null, clientId, null, true, scopeCollection, null, null, null,
null);
OAuth2Authentication oAuth = new OAuth2Authentication(authRequest, authentication);
// Add the OAuth2Authentication object to the security context
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(oAuth);
return context;
}
}
Wo ist der Code für WithMockOAuthUser und es bezieht sich auf WithSecurityContextFactory? –
@RobWinch Sorry, das ist ein Tippfehler, es ist eigentlich WithMockCustomUser, das war ein Tippfehler mit mir herumspielen, das gleiche Problem existiert.Ich hatte eine andere Schnittstelle, die eine OAuth-Authentifizierung anstelle von UsernamePasswordAuthentication erstellte – revilo
Wie sieht Ihre Sicherheitskonfiguration aus? Genau wie sieht das Web und die Methodensicherheitskonfiguration aus? –