We have OAuth2 server side application created with spring boot and i am beginner with swagger and i want to integrate it with my existing Oauth server App.
First of all, now it is also available Swagger 3.0, formally knows as OpenAPI Specification, But You asking for Swagger 2.0. So, in my opinion, the best option is to use Spring Fox - https://springfox.github.io/springfox/
You only need to add the dependency:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
Then create/reuse Spring configuration(Marked by #EnableSwagger2 annotation), explained here:
http://springfox.github.io/springfox/docs/current/#quick-start-guides
And then You can customize how swagger documents your controller in the way(eg #ApiOperation annotation):
#ApiOperation(value = "Get user by id", httpMethod = "GET")
#GetMapping("/users/{id}")
public APIUser getUser(#PathVariable("id") Long id){
...
}
Related
I have requirement to store files uploaded (using spring mvc) from client machine to jboss standalone directory .Give step by step solution
I would give the community project called Spring Content a try. This project makes it very easy to handle files by injecting the service and controller implementations for you (so that you don't need to write them yourself).
Adding it would look something like this:
pom.xml (assuming maven. Spring boot starters also available)
<!-- Java API -->
<!-- just change this depdendency if you want to store somewhere else -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-fs</artifactId>
<version>0.8.0</version>
</dependency>
<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest</artifactId>
<version>0.8.0</version>
</dependency>
StoreConfig.java
#Configuration
#EnableFilesystemStores
#Import(RestConfiguration.class)
public class StoreConfig {
#Bean
FileSystemResourceLoader fileSystemResourceLoader() throws IOException {
return new FileSystemResourceLoader(new File("/path/to/uploaded/files").getAbsolutePath());
}
}
FileStore.java
#StoreRestResource(path="files")
public interface FileStore extends Store<String> {
}
And that's it. The FileStore is essentially a generic Spring ResourceLoader. The spring-content-fs dependency will cause Spring Content to inject a filesystem-based implementation. The spring-content-rest dependency will cause Spring Content to also inject an implementation if an #Controller that forwards HTTP requests onto the methods of the FileStore service.
So you will now have a fully functional (POST, PUT, GET, DELETE) REST-based file service at /files that will use your FileStore to retrieve (and store) files in /path/to/uploaded/files on your jboss server.
So:
curl --upload-file some-image.jpg /files/some-image.jpg
will upload some-image.jpg and store it in /path/to/uploaded/files on your server.
And:
curl /files/some-image.jpg
would retrieve it again.
HTH
The injected controller also supports video streaming too, in case that is useful.
With this you could also remove all of your controller and service code as it is no longer required. Plus, as Spring Content is an abstraction over storage, in future, you could also shift to any of the other storage mediums supported by Spring Content; S3 for example.
What is the difference between using #EnableResourceServer and using HttpSecurity.oauth2ResourceServer()? Why should I use one or the other?
#EnableResourceServer is an annotation from the Spring Security OAuth project that is being replaced by new OAuth features in Spring Security 5. In essence, it loads ResourceServerConfiguration, which extends WebSecurityConfigurerAdapter and configures it, creating a filter chain that gives your application resource server functionality. Check out the docs or its source code for more info.
http.oauth2ResourceServer() is in the current Spring Security 5 reference and is the way to go. It creates a BearerTokenAuthenticationFilter that intercepts requests, extracts any Bearer Tokens and attempts to authenticate. For more details, check out the source code for the filter or for the configurer that creates the filter.
I aim to write unit test for oauth - check if user name and token was correct.
The search led me to this artical Faking OAuth SSO
For now, I am following strategy #1.
Following is the piece of code for which I need to figure out dependencies they haven't mentioned directly.
#Test
public void testGetAuthenticationInfo() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(springSecurity())
.build();
mockMvc.perform(MockMvcRequestBuilders.get("/api/token")
.with(authentication(getOauthTestAuthentication()))
.sessionAttr("scopedTarget.oauth2ClientContext", getOauth2ClientContext()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.username").value("bwatkins"))
.andExpect(jsonPath("$.token").value("my-fun-token"));
}
I managed to arrange for webApplicationContext as below -
#Autowired
private WebApplicationContext webApplicationContext;
For springSecurity() method, I am unable to get the dependency right. Whatever I searched for led me to believe that importing org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.* will get me the method but I am unable to get the pom dependency right.
Question 1: Can anybody help me with getting the dependency right?
Question 2: for such a standard thing as OAuth, isn't there a standard spring boot test package that should just require configuration to test if oauth is working fine or not
This was an issue earlier as mentioned in the issues of spring-security github. It took some time to figure out the correct version which is 4.0.2.RELEASE
https://github.com/spring-projects/spring-security/issues/3861
Adding following in pom.xml fixed the issue.
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
It seems to be, that Spring Tool Suite 3.8.3 ignores the newer MVC mapping annotations #GetMapping, #PostMapping etc. on creating the request mapping view. If a #RestController annotated class uses #RequestMapping only, all handler methods are shown in both Spring Tools => Show RequestMappings and Spring Explorer => Beans => Request Mapping. But if only the #RestController annotated class uses #RequestMapping and all handler methods uses #GetMapping, #PostMapping or #DeleteMapping, then those handler method mapping are not shown.
Boot Dashboard can show these request mapping if app is running. However, there is no support probably to show these in Request Mappings view based on annotations scanning. Feel free to raise this issue via Spring-IDE GitHub page: https://github.com/spring-projects/spring-ide/issues
I'd like to expose the backend as 'Resources' (like Restlet) and eliminate the Service Layer so a Rest Resource can direclty interact with a Dao. This way the Resource is the contract and not the Interface.
Is there a problem using #Transactional semantics on a Spring MVC 3 Controller if the transactions are managed locally by Spring? Any gotchas with Rollback and catching exceptions?
#RequestMapping(value = "/user/{userId}", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.OK)
#Transactional
public void updateUser(#PathVariable Long userId, #RequestBody ProfileUser user) {
// dao update
}
spring config:
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
I think you could run into issues here. By default Spring will use a JDK dynamic proxy to apply the transactional behaviour to your method. This relies on your controller implementing a suitable interface i.e. one which exposes an updateUser method. There is an excellent blog post on the Spring blog.
It is likely that you'll see an error due to Spring failing to find the method on the proxy.
You can use your above approach if you tell Spring to use CGLIB based proxies. This is described in the documentation here.