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
Backend interface configuration
/**
* @author wangwei
* @version v1.0.0
* @description My homepage
* @date 2010-01-10
*/
@RestController
@RequestMapping("/api/{version}/mypage")
public class MyPageController extends BaseController {
@Autowired
private UserDataService userDataService;
/**
* showdoc
* @catalog v1.0.1/My profile
* @title My Profile - Get my career track
* @description Get my career track based on token
* @method get
* @url /api/v1.0.1/mypage/findEmployeeHistory
* @param token Required string Phone number
* @param time Required int Request timestamp
* @return {"status":"200","message":"Request success", "data":[{"image":"http://192.168.4.170:8081/1545188000331-762166088940527181.png"," Orbit_id":"8","entry_time":1547006424,"company_name":"Suzhou Futong Precision Machinery Co., Ltd.","resignation_time":1547006424,"work_status":"52110"},{"image":"http: //192.168.4.170:8081/1545188000331-762166088940527181.png","orbit_id":"9","entry_time":1547006424,"company_name":"Aerospace Information","resignation_time":1547006424,"work_status":"52100 "}],"page":null,"ext":null}
* @return_param data Object Career trajectory data
* @return_param status string status
* @remark here is the note information
* @number 99
*/
@RequestMapping(value = "findEmployeeHistory", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Resp findEmployeeHistory(HttpServletRequest request, String token, String time) {
Map params = new HashMap<>();
params.put("user_id", getUserid(request));
List<Map> data = userDataService.findListByUserid(params);
return Resp.success(data);
}
Add a header to the POSTMAIN tool
Content-Type
application/json
Интерфейс Postman Test, 415 Ошибка, неподдерживаемый тип носителя
Описание проблемы:
Когда вы используете интерфейс тестирования почтальона, у вас будет следующая ошибка.
Решение:
Откройте окно заголовка в возвращенном сообщении, чтобы просмотреть значение в разделе «Content».
В поле заголовка в сообщении значение значения значения содержимого значения изменяется на значение содержимого типа возвратной информации.
Я
Принцип Объяснение:
415 Ошибка, неподдерживаемый тип носителя, указывающий, что отправленный медиа-файл не поддерживается. В заголовке в забранной информации HTML принимает формат приложения / JSON, но в отправителе отправитель X-www-urlencoded: Charset = UTF-8 отправляется, видимо HTML не распознается.