Unable to receive token from webapi and get displayed in Angular 6 - c#

I am using an token based authorization using .net as backend and angular 6 in front end and I have successfully able to receive the token from the server, but after authenticate method is called from the UI the token is reached to UI.
I am using an token based authorization using .net as backend and angular 6 in front end and I have successfully able to receive the token from the server, but after authenticate method is called from the UI I get an error;
TypeError: Cannot read property 'headers' of null.
C# webapi code for authenticate method is
[a.Route("api/authenticate/")]
[a.HttpPost]
public c.Http.HttpResponseMessage Authenticate([FromBody]User usr)
{
if (string.IsNullOrEmpty(usr.UserName) && string.IsNullOrEmpty(usr.Password))
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotAcceptable);
message.Content = new c.Http.StringContent("Not Valid Request");
return message;
}
else
{
if (auth.ValidateKeys(usr.UserName, usr.Password))
{
//var pass1 = EncryptionLibrary.DecryptText(ClientKeys.Password);
var pass = EncryptionLibrary.EncryptText(usr.Password);
var clientkeys = auth.GetClientKeysDetailsbyCLientIDandClientSecert(usr.UserName, pass);
if (clientkeys == null)
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotAcceptable);
message.Content = new c.Http.StringContent("Not Valid Request");
return message;
}
else
{
if (auth.IsTokenAlreadyExists(clientkeys.UserId))
{
auth.DeleteGenerateToken(clientkeys.UserId);
var response= GenerateandSaveToken(clientkeys);
return response;
}
else
{
var response= GenerateandSaveToken(clientkeys);
return response;
}
}
}
else
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotFound);
message.Content = new c.Http.StringContent("InValid Keys");
return new c.Http.HttpResponseMessage { StatusCode = c.HttpStatusCode.NotAcceptable };
//return new HttpResponseMessage { StatusCode = HttpStatusCode.NotAcceptable };
}
}
}
GenerateandSaveToken method is as follows:
private c.Http.HttpResponseMessage GenerateandSaveToken(User clientkeys)
{
var IssuedOn = DateTime.Now;
var newToken = auth.GenerateToken(clientkeys, IssuedOn);
TokensManager token = new TokensManager();
//token.TokenId = 0;
token.TokenKey = newToken;
token.UserID = clientkeys.UserId;
token.IssuedOn = IssuedOn;
token.ExpiresOn = DateTime.Now.AddMinutes(Convert.ToInt32(ConfigurationManager.AppSettings["TokenExpiry"]));
token.CreatedOn = DateTime.Now;
var result = auth.InsertToken(token);
if (result == 1)
{
c.Http.HttpResponseMessage response = new c.Http.HttpResponseMessage();
//response = Content(c.HttpStatusCode.Found, "Authorized");
response.Headers.Add("Token", newToken);
response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["TokenExpiry"]);
response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
return response;
}
else
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotAcceptable);
message.Content = new c.Http.StringContent("Error in Creating Token");
return message;
}
}
In angular code is as follows:
AuthenticationService
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
private baseUrl: string = environment.apiUrl;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(User) {
console.log("User values check"+User)
const headers = new HttpHeaders()
//headers.append('Content-Type', 'application/json');
.set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any>(this.baseUrl+'api/authenticate/',User, {headers,responseType: "json"})
.pipe(map((user => {
// login successful if there's a jwt token in the response
console.log("user values"+user.headers.get('Token'))
if (user && user.headers.get('Token')) {
console.log("Reached tokens!!!")
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
/* this.http.put(apiURL, JSON.stringify(json),
{observe:'response'}).subscribe((res:Response) =>
console.log(res));*/
return user;
})));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
Calling the above login method from LoginComponent as follows:
export class LoginComponent implements OnInit {
response:{}
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
usr:User[];
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService,
) {
// redirect to home if already logged in
if (this.authenticationService.currentUserValue) {
this.router.navigate(['/']);
}
}
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
onSubmit() {
this.submitted = true;
let frm= JSON.stringify(this.loginForm.value);
console.log("printing form values"+this.loginForm.value)
console.log("frm values"+frm)
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
/* .subscribe( t =>
this.CatalogForm.patchValue
({Category:t,SubCategory:t,Description:t,ItemName:t,IAP_Number:t})
, err =>
console.log("Error messgae:",this.errorMessage)
);*/
this.loading = true;
this.authenticationService.login(frm)
.pipe(map((data:Response)=>data.json()))
.subscribe(
data => {
this.response = data,
console.log('Response'+this.response);
//this.loginForm.patchValue({User:data});
this.router.navigate([this.returnUrl]);
},
error => {
console.log("Reached Login error!!!")
this.alertService.error(error);
this.loading = false;
});
}
}
alertService as below:
#Injectable({ providedIn: 'root' })
export class AlertService {
private subject = new Subject<any>();
private keepAfterNavigationChange = false;
constructor(private router: Router) {
// clear alert message on route change
console.log("inside alert service!!!!")
router.events.subscribe(event => {
if (event instanceof NavigationStart) {
console.log("event:"+event)
if (this.keepAfterNavigationChange) {
// only keep for a single location change
console.log("inside Navigation Start!!!!")
this.keepAfterNavigationChange = false;
} else {
// clear alert
console.log("inside Navigation Start else method!!!!")
this.subject.next();
}
}
});
}
success(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
console.log("inside Success Start!!!!")
this.subject.next({ type: 'success', text: message });
}
error(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
console.log("Navigation value"+this.keepAfterNavigationChange);
console.log("inside Navigation error!!!!")
console.log("message"+message)
this.subject.next({ type: 'error', text: message });
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Please note I am able to receive token from the server and the token is exposed as well from server side using below code
config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*", exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });
config.MapHttpAttributeRoutes();
config.EnableCors();
I should be successfully able to receive the token from the server and ui should display an success message as in below html
<div *ngIf="message"
[ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">
{{message.text}}</div>

In your AuthenticationService's login method, use this, you'll have to pass observe: 'response' as well to the HttpOptions argument, in order to get the complete response. Something like this:
export class AuthenticationService {
private currentUserSubject: BehaviorSubject < User > ;
public currentUser: Observable < User > ;
private baseUrl: string = environment.apiUrl;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject < User > (JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(User) {
console.log("User values check" + User)
const headers = new HttpHeaders({
'Content-Type', 'application/x-www-form-urlencoded'
});
return this.http.post < any > (this.baseUrl + 'api/authenticate/', User, {
headers,
responseType: "json",
observe: 'response'
})
.pipe(map((user => {
// login successful if there's a jwt token in the response
console.log("user values" + user.headers.get('Token'))
if (user && user.headers.get('Token')) {
console.log("Reached tokens!!!")
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
/* this.http.put(apiURL, JSON.stringify(json),
{observe:'response'}).subscribe((res:Response) =>
console.log(res));*/
return user;
})));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}

Related

DELETE request works from insomnia/postman but not from the frontend

DELETE request give 204 response code from Insomnia/Postman, But from the frontend it gives error for Delete request.
Please find my Service code below :
public bool Dissociate(string envCode, string serialNumber, string gatewayType)
{
envCode.ThrowIfNull();
serialNumber.ThrowIfNull();
gatewayType.ThrowIfNull();
if (!IsAssociated(envCode, serialNumber, gatewayType))
{
_logService.Warn($"DspService - Dissociate - {gatewayType} {serialNumber} not associated to DSP tenant on environment {envCode}");
return false;
}
EnvironmentSettings dspEnvSettings = GetEnvironmentSettings(envCode);
string baseUri = DspHelper.GetBaseUriByAction(dspEnvSettings, DspActionType.Dissociate);
string dspDeviceId = DspHelper.BuildDeviceId(serialNumber, gatewayType, true);
string uri = $"{baseUri}/registry/devices/{dspDeviceId}/claim";
var body = new
{
Claimable = true
};
try
{
var authToken = GetAuthorizationHeader(dspEnvSettings, DspActionType.Dissociate);
RunDspCommand<bool>(dspEnvSettings, uri, authToken, body, HttpMethod.Put, DspActionType.Dissociate);
return true;
}
catch (Exception e)
{
_logService.ErrorException(e, $"DspService - Dissociate - Error dissociating {gatewayType} {serialNumber} on environment {envCode}. {uri}");
throw;
}
}
Please find my insomnia response:
CONTROLLER :
[AcceptVerbs("DELETE")]
[Route("dissociate")]
public bool Dissociate([FromUri] string gatewayType, [FromUri] string gatewaySerial)
{
if (string.IsNullOrEmpty(gatewaySerial) || string.IsNullOrEmpty(gatewayType))
{
this.BadRequestResponse();
}
var connectedUser = this.permissionService.GetConnectedUser();
this.permissionService.CheckRolePermission(connectedUser.Role, PermissionConstant.DissociateComX);
bool hasSucceeded = this.dspService.Dissociate(connectedUser.CurrentEnvironment, gatewaySerial, gatewayType);
if (hasSucceeded)
{
this.applicationDataAccess.LogAction(connectedUser.CurrentEnvironment, connectedUser.Email, LogActionConstants.Action.DissociateComX, string.Format(LogActionConstants.Message.DissociateComX, gatewayType, gatewaySerial));
}
else
{
this.BadRequestResponse("cannot deprovioned comx");
}
return hasSucceeded;
}
It gives the exception in the Service Code
RunDspCommand<bool>(dspEnvSettings, uri, authToken, body, HttpMethod.Put, DspActionType.Dissociate);
Below is my front end code.
controller.ts
dissociateGateway() {
if (!this.isDspGateway || this.isLoadingDspState || this.isDissociating
|| this.gateway.FirmwareUpgradeWorkflow || this.gateway.DeleteGatewayWorkflow
|| !this.isAssociated()) {
return;
}
this.modalService.confirm(
`The ${this.gateway.Type} ${this.gateway.SerialNumber} will be dissociated from its DSP tenant ${this
.dspGatewayState.Tenant}.`,
'Are you sure you want to dissociate the gateway from DSP tenant?')
.then(() => {
this.isDissociating = true;
this.dspService.dissociate(this.gateway.Type, this.getDeviceId())
.then(() => this.getDspGatewayState())
.catch((e) => {
if (e) {
this.modalService.error('Error dissociating the gateway. Please retry later');
}
})
.finally(() => this.isDissociating = false);
});
}
service.ts
dissociate(gatewayType: string, gatewaySerial: string): ng.IPromise<boolean> {
var uri = this.ROUTES.dissociate
.replace('{:gatewayType}', gatewayType.toString())
.replace('{:gatewaySerial}', gatewaySerial);
return this.restService
.delete(uri, null)
.then((response: any) => {
return response;
})
.catch((response: any) => {
return this.$q.reject(response);
});
}
Path :
dissociate: '/dsp/dissociate?gatewaytype={:gatewayType}&gatewaySerial={:gatewaySerial}',
If you need more information please comment below.
Please help me. Thanks in Advance.

Telegram bot in asp.net core 3.1 is giving no data in Update object

I am developing telegram notifications in my existing asp.net core 3.1 project. I have written below code in controller.
#region Telegram
TelegramBotClient _botService;
private const string token = "332435:45345345345dflskdfjksdjskdjflkdd";
[HttpPost("Update")]
[AllowAnonymous]
public async Task<IActionResult> Update([FromBody] Update update)
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (_botService == null)
_botService = new TelegramBotClient(token);
if (update.Type != UpdateType.Message)
return Ok(new Response
{
code = (int)HttpStatusCode.OK,
status = "Ok",
message = "Success"
});
var message = update.Message;
try
{
_logger.LogInformation("Received Message from {0}", message.Chat.Id);
switch (message.Type)
{
case MessageType.Text:
if (message.Text.Contains("/Reset"))
{
//Delete(string chatid)
var response = _UserRepository.DeleteTeleBotChatID(message.Chat.Id);
if (response)
await _botService.SendTextMessageAsync(message.Chat.Id, "You have successfully unsubscribed.");
else
await _botService.SendTextMessageAsync(message.Chat.Id, "You are not registered yet.");
}
else
if (message.Text.Contains("/") && !message.Text.ToLower().Contains("/start"))
{
var user = Crypto.decrypt(Encoding.UTF8.GetString(Convert.FromBase64String(message.Text.Split('/').Last())));
var response = _UserRepository.UpdateTeleBotChatIDByUser(new TeleBotModel() { ChatId = message.Chat.Id, Username = user });
if (response)
await _botService.SendTextMessageAsync(message.Chat.Id, $"You have successfully subscribe notifications for {user}.");
else
await _botService.SendTextMessageAsync(message.Chat.Id, "Username is not valid");
// var chat=modifyus(string username,chatid)
}
else
{
await _botService.SendTextMessageAsync(message.Chat.Id, "Enter your encrypted username.\n Type /Reset to unsubscribe.");
}
break;
case MessageType.Photo:
// Download Photo
var fileId = message.Photo.LastOrDefault()?.FileId;
var file = await _botService.GetFileAsync(fileId);
var filename = file.FileId + "." + file.FilePath.Split('.').Last();
using (var saveImageStream = System.IO.File.Open(filename, FileMode.Create))
{
await _botService.DownloadFileAsync(file.FilePath, saveImageStream);
}
await _botService.SendTextMessageAsync(message.Chat.Id, "Thx for the Pics");
break;
}
}
catch (Exception exp)
{
//LoggerSimple.Error(exp);
await _botService.SendTextMessageAsync(message.Chat.Id, "Wrong Bot command");
}
return Ok(new Response
{
code = (int)HttpStatusCode.OK,
status = "Ok",
message = "Success"
});
}
[HttpPost]
public async Task<IActionResult> sendTeleMsg(TelegramMessgae Data)
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if (_botService == null)
_botService = new TelegramBotClient(token);
//check username exist
long ChatId = _UserRepository.GetChatIdByUsername(Data.Username);
if (ChatId == -1)
{
return Ok(new Response
{
error = "true",
code = HttpStatusCode.BadRequest,
status = HttpStatus.OK,
message = "Not registered with telegram bot"
});
}
try
{
await _botService.SendTextMessageAsync(ChatId, string.Format("*{0}*\n{1}", parseMText(Data.Subject), parseMText(Data.Message)), ParseMode.Markdown);
return Ok(new Response
{
code = HttpStatusCode.OK,
status = HttpStatus.OK,
message = "Message Sent"
});
}
catch (Exception exp)
{
//if wrong chatid
_UserRepository.DeleteTeleBotChatID(ChatId);
return Ok(new Response
{
error = "true",
code = HttpStatusCode.BadRequest,
status = HttpStatus.OK,
message = exp.Message
});
}
}
private string parseMText(string txt)
{
var vs = new string[] { "*", "_", "`", "[", "]" };
foreach (var item in vs)
{
txt = txt.Replace(item, "\\" + item);
}
return txt;
}
#endregion
then used ngrok for tunnelling and exposed localhost so that I can connect with telegram bot. After creating and subscribing the bot, I am able to receive a breakpoint in above Update method but data was nothing. I sent messages on bot but always there is no data in update object. See below screenshot.
I am unable to figure-out the issue in the code. Can anyone pls help?
Calling AddNewtonsoftJson() function in starup.cs file fixed the issue.
services.AddControllers().AddNewtonsoftJson();

In ASP.Net Zero, Why I am not getting records when I try to execute an API using Angular UI but when I use swagger It returns the expected value?

ScreenCast Video Screen Capture: https://www.screencast.com/t/iwbNw1qwzGa
When you see the screen capture. It will show the first part where I demonstrate the calling of API using the Angular UI and the second part is where I use Swagger UI to call the API. You can see there that the first part displays calls the API and returns 0 records on the response when executing the GetAll() function of the default method of the ASP.Net Zero. But in the second part where it executes the API via swagger it returns the expected value from the DB. Please help on this issue. Thanks in advance.
See details of my code:
Component
ngOnInit(): void {
this.loadGroupHeaderCombo();
}
​
loadGroupHeaderCombo()
{
this._groupHeadersService.getAllGroupHeaderCombo()
.pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
.subscribe(result =>{
this.groupHeaderNamesSelectItems = _.map(result.groupHeaderNames, function(groupHeader) {
return {
label: groupHeader.displayText, value: groupHeader.value
};
});
return result;
});
}
Service-proxies
getAllGroupHeaderCombo(): Observable<GetGroupHeaderOutput> {
let url_ = this.baseUrl + "/api/services/app/GroupHeaders/GetAllGroupHeaderCombo";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGetAllGroupHeaderCombo(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGetAllGroupHeaderCombo(<any>response_);
} catch (e) {
return <Observable<GetGroupHeaderOutput>><any>_observableThrow(e);
}
} else
return <Observable<GetGroupHeaderOutput>><any>_observableThrow(response_);
}));
}
protected processGetAllGroupHeaderCombo(response: HttpResponseBase): Observable<GetGroupHeaderOutput> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = GetGroupHeaderOutput.fromJS(resultData200);
return _observableOf(result200);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<GetGroupHeaderOutput>(<any>null);
}
API Function
public async Task<GetGroupHeaderOutput> GetAllGroupHeaderCombo()
{
var output = new GetGroupHeaderOutput();
//Issue is ocurring here
var x = _groupHeaderRepository.GetAll();
//GroupHeader
output.GroupHeaderNames = _groupHeaderRepository
.GetAll()
.Select(s => new ComboboxItemDto
{
DisplayText = s.GroupTitle,
IsSelected = false
})
.ToList();
}
what i notice are 1.from your API your change list async
2.clean your service.proxy file and run 'refresh.bat' in your nswag file to generate new proxies.

Login with Facebook C#

I have an infinty loop of refresh when I try to log in with facebook on my site ,
I have declared a script afer the the body tag that was
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '337323336385***', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// Additional initialization code here
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// TODO: Handle the access token
//alert("check");
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/FacebookLogin.ashx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
//alert("Please ");
} else {
// the user isn't logged in to Facebook.
//alert("jj");
alert("Please Sign into your account to access the site");
}
});
};
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
as you see this function it's calling a C# function that's in the file of FacebookLogin.ashx this function is responsable for creating a Session variable containing the data for the user
public void ProcessRequest(HttpContext context)
{
var accessToken = context.Request["accessToken"];
context.Session["AccessToken"] = accessToken;
HttpCookie cookie = new HttpCookie("FB");
string accessToken2 = context.Session["AccessToken"].ToString();
Facebook.FacebookClient client = new Facebook.FacebookClient(accessToken2);
dynamic result = client.Get("me", new { fields = "name,id,link,gender" });
cookie["FBID"] = result.id;
context.Response.Cookies.Add(cookie);
context.Response.Redirect("/login.aspx");
}
after that in the pageload I check for the existance of this session variable
string accessToken;
FacebookClient client;
dynamic result;
if (Session["AccessToken"] != null)
{
accessToken = Session["AccessToken"].ToString();
client = new FacebookClient(accessToken);
result = client.Get("me", new { fields = "name,id,link,gender" });
if (gb.CheckExistanceByFBID(result.id))
{
string FBID = result.id;
var userDetails = context.Users.Where(x => x.FBID == FBID).Select(x => x).First();
HttpCookie cookie = new HttpCookie("userData", userDetails.UserName);
cookie.Expires = DateTime.Now.AddMonths(2);
cookie["UserName"] = userDetails.UserName;
cookie["UserID"] = userDetails.UserID.ToString();
cookie["Password"] = userDetails.Password;
cookie["isAdmin"] = userDetails.Admin.ToString();
cookie["Name"] = userDetails.DisplayName;
cookie["FBID"] = userDetails.FBID;
Response.Cookies.Add(cookie);
System.Web.Security.FormsAuthentication.SetAuthCookie(userDetails.UserName, true);
System.Web.Security.FormsAuthentication.Timeout.Add(new TimeSpan(40, 0, 0, 0));
Response.Redirect("/Default.aspx");
}
else
{
//var accessToken = Session["AccessToken"].ToString();
//var client = new FacebookClient(accessToken);
//dynamic result = client.Get("me", new { fields = "name,id,link,gender" });
accessToken = Session["AccessToken"].ToString();
client = new FacebookClient(accessToken);
result = client.Get("me", new { fields = "name,id,link,gender" });
FBRegisterPanel.Visible = false;
MainRegisterPanel.Visible = true;
txtUserName.Text = result.name;
}
}
the problem that I have an infinty loop of refresh after I click the facebook login button !
I had the same problem.
When login.aspx loads, the JS is executed, which posts the form to FacebookLogin.ashx, which redirects to login.aspx, which means the JS is run again and the cycle continues.
(Hopefully) by doing the following, if an OAuth token is stored, the if-statement is made false so the script to submit the form to FacebookLogin.ashx is never executed.
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected' && "<%= Session["AccessToken"].ToString() %>" == "") { ... }
Note: make sure that Session["AccessToken"] contains an empty string even if there is no access token to store, because:
the JS is looking for an empty string in Session["AccessToken"] to make the if-statement true.
if left null, I think <%= Session["AccessToken"].ToString() %> will throw a null reference exception.
You can do this by execuing this on Page_Init:
if (Session["AccessToken"] == null)
{
Session["AccessToken"] = string.Empty;
}

why is HttpContext.Current.Request.Cookies[fullCookie] is always NULL when checking FB connectivity?

I am totally new in using FB API and i am trying to post to facebook wall from my Asp.net application.
I have got the Appkey and secret key from FB and just trying to follow
the code to post in FB wall.
LINK : http://kennetham.com/2010/07/21/facebook-api-asp-net/
The problem i am facing now is, in my ConnectAuthentication Class, HttpContext.Current.Request.Cookies[fullCookie] is always NULL. Due to that, when i check for the FB connectivity by "if (ConnectAuthentication.isConnected())" in my pageload, it always returns false and it does not run the code inside condition.
Why is that? Am i missing something ?
ConnectAuthentication Class
public class ConnectAuthentication
{
public ConnectAuthentication()
{
}
public static bool isConnected()
{
return (SessionKey != null && UserID != -1);
}
public static string ApiKey
{
get
{
return ConfigurationManager.AppSettings["APIKey"];
}
}
public static string SecretKey
{
get
{
return ConfigurationManager.AppSettings["Secret"];
}
}
public static string SessionKey
{
get
{
return GetFacebookCookie("session_key");
}
}
public static long UserID
{
get
{
long userID = -1;
long.TryParse(GetFacebookCookie("user"), out userID);
return userID;
}
}
private static string GetFacebookCookie(string cookieName)
{
string retString = null;
string fullCookie = ApiKey + "_" + cookieName;
if (HttpContext.Current.Request.Cookies[fullCookie] != null)
retString = HttpContext.Current.Request.Cookies[fullCookie].Value;
return retString;
}
}
Here is how the ConnectAuthentication Class is used in my page load :
if (ConnectAuthentication.isConnected())
{
Facebook.Session.ConnectSession session = new Facebook.Session.ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey);
_connectSession = new ConnectSession(ConnectAuthentication.ApiKey, ConnectAuthentication.SecretKey);
Api _facebookAPI = new Api(_connectSession);
_connectSession.UserId = ConnectAuthentication.UserID;
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
//Display user data captured from the Facebook API.
Facebook.Schema.user user = api.Users.GetInfo();
string fullName = user.first_name + " " + user.last_name;
Panel1.Visible = true;
Label1.Text = fullName;
}
else
{
//Facebook Connect not authenticated, proceed as usual.
}
}
This code worked perfectly...
<input type="button" id="fblogin" value="Login to Facebook" disabled="disabled" style="display:none"/>
<fb:login-button v="2" length="long" onlogin="window.location = 'Default.aspx'">Login to Facebook</fb:login-button>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '<%: Facebook.FacebookApplication.Current.AppId %>',
cookie: true,
xfbml: true,
oauth: true
});
function facebooklogin() {
FB.login(function (response) {
if (response.authResponse) {
// user authorized
// make sure to set the top.location instead of using window.location.reload()
top.location = '<%= this.ResolveCanvasPageUrl("~/") %>';
} else {
// user cancelled
}
}, { scope: '<%: string.Join(",", ExtendedPermissions) %>' });
};
$(function () {
// make the button is only enabled after the facebook js sdk has been loaded.
$('#fblogin').attr('disabled', false).click(facebooklogin);
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
</script>

Categories

Resources