I am implementing spring security with oauth2 and jwt.
the below is my login function
function doLogin(loginData) {
$.ajax({
url : back+"/auth/secret",
type : "POST",
data : JSON.stringify(loginData),
contentType : "application/json; charset=utf-8",
dataType : "json",
async : false,
success : function(data, textStatus, jqXHR) {
setJwtToken(data.token);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("an unexpected error occured: " + errorThrown);
window.location.href= back+'/login_page.html';
}
});
}
And down I have the Controller
@RequestMapping(value = "auth/secret", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
System.out.println();
logger.info("authentication request : " + authenticationRequest.getUsername() + " " + authenticationRequest.getPassword());
// Perform the security
System.out.println( authenticationRequest.getUsername()+"is the username and "+authenticationRequest.getPassword());
final Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
logger.info("authentication passed");
// Reload password post-security so we can generate token
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails, device);
logger.info("token " + token);
// Return the token
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
But when I try the post request with the postman it shows me
{
"timestamp": 1488973010828,
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'multipart/form-data;boundary=----WebKitFormBoundaryY4KgeeQ9ONtKpvkQ;charset=UTF-8' not supported",
"path": "/TaxiVis/auth/secret"
}
But when I do cosole.log(data)
in the ajax call it prints the token?I could not figure out what is wrong.Any help is appreciated.
I have used Jersey Restful API to create a web service and I have the below:
@POST
@Path("/process/")
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces({MediaType.APPLICATION_JSON})
public Response process(@FormDataParam("upload") InputStream is, @FormDataParam("upload") FormDataContentDisposition formData);
I have used the following dependencies:
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1-m01</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey.contribs/jersey-multipart -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-server -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/jsr311-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
Configuration in Web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/ws-context.xml</param-value>
</context-param>
in ws-context.xml, I have this part:
<bean id="restManagerService" class="com.rs.service.impl.RestManagerServiceImpl">
<property name="restRequestService" ref="restRequestService" />
</bean>
<bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
</bean>
<jaxrs:server id="userManagerREST" address="/rest/v1">
<jaxrs:serviceBeans>
<ref bean="restManagerService" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean='jsonProvider' />
<ref bean='multipartResolver' />
<bean class="com.rs.exception.ExceptionHandler" />
</jaxrs:providers>
</jaxrs:server>
Now to test this, I am using Postman app to send a Post request. Below is the content from the code window:
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryxxxxxxxxx
------WebKitFormBoundaryxxxxxxxxx
Content-Disposition: form-data; name="upload"; filename="test.json"
I have already referred to several samples on google, like this , this, and this and I see that I have provided the parameters correctly but I still get 415 Unsupported Media Type error in Postman. I have several other web services in this project which consumes MediaType application/json so the project configuration shouldn’t be an issue.
Can somebody please shed some light as to what is wrong here.
UPDATE: Added additional details related to all jersey and WS related dependencies used and important content from the web.xml file
Loading
Интерфейс Postman Test, 415 Ошибка, неподдерживаемый тип носителя
Описание проблемы:
Когда вы используете интерфейс тестирования почтальона, у вас будет следующая ошибка.
Решение:
Откройте окно заголовка в возвращенном сообщении, чтобы просмотреть значение в разделе «Content».
В поле заголовка в сообщении значение значения значения содержимого значения изменяется на значение содержимого типа возвратной информации.
Я
Принцип Объяснение:
415 Ошибка, неподдерживаемый тип носителя, указывающий, что отправленный медиа-файл не поддерживается. В заголовке в забранной информации HTML принимает формат приложения / JSON, но в отправителе отправитель X-www-urlencoded: Charset = UTF-8 отправляется, видимо HTML не распознается.
The error information is as follows:
{ "timestamp": "2018-12-06T01:37:11.184+0000", "status": 415, "error": "Unsupported Media Type", "message": "Content type 'text/plain;charset=UTF-8' not supported", "path": "/testgu/ycyzharry" }
Cause of problem:
Media type refers to Internet media type, Internet media type, also known as MIME type. In the HTTP protocol message header, content type is used to represent the media type information in the specific request
for example: content type: text/HTML; charset:utf-8;
common media format types are as follows:
text/html :HTML format text/plain : Plain text format text/xml : XML format image/gif : gif image format image/jpeg : jpg image format image/png : png image format
Media format type starting with application:
application/xhtml+xml : XHTML format application/xml : XML data format application/atom+xml : Atom XML aggregation format application/json : JSON data format application/pdf : pdf format application/msword : Word document format application/octet-stream : Binary stream data (e.g. common file downloads) application/x-www-form-urlencoded : <form encType=""> in the default encType, form form data is encoded as key/value format and sent to the server (the default form submission format of the data)
Another common media format is used when uploading files:
multipart/form-data : This format is used when file uploads are required in the form
The above is the content format of content type we often use. The message message in this example indicates that the post request does not support the “text/plain” plain text format type
Solution: select the “application/JSON” JSON data format type to send the post request, and the interface return value is successfully obtained